package com.zhiche.lisa.oms.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zhiche.lisa.core.enums.InterfaceEventEnum;
import com.zhiche.lisa.core.enums.TableStatusEnum;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.supports.RestfulResponse;
import com.zhiche.lisa.core.utils.HttpClientUtil;
import com.zhiche.lisa.core.utils.SnowFlakeId;
import com.zhiche.lisa.oms.dao.mapper.OrderMapper;
import com.zhiche.lisa.oms.dao.model.*;
import com.zhiche.lisa.oms.dao.model.bo.GenerateOrderBO;
import com.zhiche.lisa.oms.dao.model.bo.ShipLineInfoBO;
import com.zhiche.lisa.oms.dao.model.bo.ShippingInfoBO;
import com.zhiche.lisa.oms.dto.*;
import com.zhiche.lisa.oms.enums.FailureDataType;
import com.zhiche.lisa.oms.enums.FourPeopleEnum;
import com.zhiche.lisa.oms.service.*;
import com.zhiche.lisa.oms.vo.*;
import com.zhiche.lisa.tms.dao.model.*;
import com.zhiche.lisa.tms.dto.OmsOrder;
import com.zhiche.lisa.tms.dto.OmsOrderItem;
import com.zhiche.lisa.tms.dto.OmsOrderLocation;
import com.zhiche.lisa.tms.dto.OrderAssignDTO;
import com.zhiche.lisa.tms.service.*;
import com.zhiche.lisa.util.ErpUtil;
import com.zhiche.lisa.util.MdmUtil;
import com.zhiche.lisa.util.TokenUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

//import com.zhiche.lisa.repos.mapper.oms.Ord

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author qichao
 * @since 2018-06-18
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    private static final Logger LOGGER = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Autowired
    private IOrderItemService orderItemService;
    @Autowired
    private IOrderContactService orderContactService;
    @Autowired
    private IOrderLocationService orderLocationService;
    @Autowired
    private IOrderAssignService orderAssignService;
    @Autowired
    private ILocationService locationService;
    @Autowired
    private TokenUtil tokenUtil;
    @Autowired
    private MdmUtil mdmUtil;
    @Autowired
    private ErpUtil erpUtil;
    @Autowired
    private IShipOrderService iShipOrderService;
    @Autowired
    private InterfaceCompensationService interfaceCompensationService;
    @Autowired
    private SnowFlakeId snowFlakeId;
    @Autowired
    private IShipmentService shipmentService;
    @Autowired
    private IShipOrderService shipOrderService;
    @Autowired
    private IShipTaskService shipTaskService;
    @Autowired
    private IShipOrderItemService shipOrderItemService;
    @Autowired
    private IShipTaskContactService shipTaskContactService;
    @Autowired
    private IShipTaskLocationService shipTaskLocationService;
    @Autowired
    private IShipmentDetailService shipmentDetailService;
    @Autowired
    private IOtmShipmentService otmShipmentService;
    @Autowired
    private ImportLogHistoryService importLogHistoryService;
    @Autowired
    private TmsExplogLineService explogLineService;

    @Value("${erp.getNewestShipByLicenseUrl}")
    private String getNewestShipByLicenseUrl;
    //连接超时时间
    @Value("${erp.socketTimeout}")
    private int socketTimeout;
    @Value("${erp.rmtILSShipUrl}")
    private String rmtILSShipUrl;
    @Value("${lisa.lspm.authedCarrierPlateURL}")
    private String authedCarrierPlateURL;
    @Value("${uaa.getTentUrl}")
    private String getTentUrl;
    @Value("${security.oauth2.client.access-token-uri}")
    private String getTokenUrl;
    @Value("${security.oauth2.client.clientId}")
    private String getClinetId;
    @Value("${security.oauth2.client.clientSecret}")
    private String getClientSecret;
    @Value("${lisa.lspm.getCarrierInfoByPlate}")
    private String getCarrierInfoByPlate;
    @Value("${integration.getPriceAndMilesUrl}")
    private String getPriceAndMilesUrl;
    @Value("${integration.url}")
    private String integrationUrl;
    @Value("${lisa.bms.insertPriceIncomingUrl}")
    private String insertPriceIncomingUrl;
    @Value("${lisa.bms.updateIncomingPriceByTaskCodeUrl}")
    private String updateIncomingPriceByTaskCodeUrl;
    @Value("${lisa.bms.deletePriceIncomingUrl}")
    private String deletePriceIncomingUrl;
    @Value("${integration.queryListOriginationUrl}")
    private String queryListOriginationUrl;
    @Value("${lisa.lspm.getDriverInfoById}")
    private String getDriverInfoById;
    @Value("${lisa.lspm.isUnlcnFleetDriverUrl}")
    private String isUnlcnFleetDriverUrl;
    @Value("${integration.queryCiamsNameList}")
    private String queryCiamsNameList;
    @Value("${lisa.lspm.queryFleetBasic}")
    private String queryFleetBasic;

    @Override
    public void getAuthedCarrierPlate() {
        List<TechAccount> techAccountList = getToken();

        for (TechAccount techAccount : techAccountList) {
            if (Objects.nonNull(techAccount.getTechAccountIdentifier())) {
                String token = getTenantToken(techAccount.getTechAccountIdentifier());
                if (!StringUtils.isEmpty(token)) {
                    List<String> plateList = getCarrierPlates(token, techAccount.getId());
                    if (CollectionUtils.isNotEmpty(plateList)) {
//                    String licenses = StringUtils.join(plateList.toArray(), ",");
                        createOrderByErpShipment(token, plateList, techAccount.getId());
//                    generateOrder(token, plateList);
                    }
                }
            }
        }
    }

    @Override
    public void createOrderByErpShipment(String authorization, List<String> plateList, Long teanantId) throws
            BaseException {
        for (String license : plateList) {
            // 则调用接口，抓取调度指令
            ShippingInfoBO shippingInfoBO = getNewestShipByERP(license);
            if (!Objects.isNull(shippingInfoBO)) {
                Wrapper<Order> orderWrapper = new EntityWrapper<>();
                orderWrapper.eq("customer_order_id", shippingInfoBO.getVcshipno());
                List<Order> orderList = baseMapper.selectListNoTenant(orderWrapper);
                // 如果订单不存在就插入，存在则更新
                if (CollectionUtils.isEmpty(orderList)) {
                    // 插入
                    this.createOrder(authorization, shippingInfoBO, teanantId);
                }
            }
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createOrder(String authorization, ShippingInfoBO shippingInfoBO, Long teanantId) {

        ShipmentAutoDTO shipmentAutoDTO = new ShipmentAutoDTO();

        // 发运指令下所有明细
        List<ShipLineInfoBO> shipLineInfoBOList = shippingInfoBO.getShipLineInfoBOList();
        // 根据明细生成的订单数
        List<GenerateOrderBO> generateOrderBOList = new ArrayList<>();

        // 组装头和明细关系
        for (ShipLineInfoBO shipLineInfoBO : shipLineInfoBOList) {
            GenerateOrderBO generateOrderBO = getGenerateOrderBO(shipLineInfoBO, generateOrderBOList);
            generateOrderBO.addShipLineInfoBO(shipLineInfoBO);
        }

        for (GenerateOrderBO generateOrderBO : generateOrderBOList) {
            //创建订单
            Order order = new Order();
            // 订单编号
            String code = "CO" + snowFlakeId.nextId();
            order.setCode(code);
            // 订单备注
            order.setComment(shippingInfoBO.getVcmemo());
            // 业务类型
            order.setTos("fleet");
            // 客户下单时间
            order.setGmtIssue(shippingInfoBO.getDtdate());
            // 系统创建时间
            order.setGmtCreate(new Date());
            // 客户标识
            order.setCustomerId("unlcn");
            // 客户订单编号
            order.setCustomerOrderId(shippingInfoBO.getVcshipno());

            order.setTenantId(teanantId);

            // 插入订单
            insert(order);

            //创建联系人
            OrderContact orderContact = new OrderContact();
            // 联系人姓名
            orderContact.setContactsName(shippingInfoBO.getVcdrivername());
            // 联系人电话
            orderContact.setContactsPhone(shippingInfoBO.getVcmobile());
            // 订单编码
            orderContact.setOrderCode(order.getCode());
            orderContact.setTenantId(teanantId);
            // 保存订单各类联系人信息
            orderContactService.insert(orderContact);

            order.setOrderContact(orderContact);

            // 判断订单明细里的提货地点信息是否存在，不存在则插入
            LocationVo startLocation = locationService.getLocationByValue("发货点", generateOrderBO.getVcstartcityname());
            if (startLocation == null) {
                // 插入

                startLocation = locationService.insertOrUpdateLocation("发货点",
                        generateOrderBO.getVcstartcityname(), generateOrderBO.getVcstartcityname(), null, teanantId);
                if (startLocation == null) {
                    throw new BaseException("获取提货点信息失败");
                }
            }

            // 判断订单明细里的交货地点信息是否存在，不存在则插入
            LocationVo endLocation = locationService.getLocationByValue("交货点", generateOrderBO.getVcendcityname());
            if (endLocation == null) {
                // 插入
                endLocation = locationService.insertOrUpdateLocation("交货点",
                        generateOrderBO.getVcendcityname(), generateOrderBO.getVcendcityname(), null, teanantId);
                if (endLocation == null) {
                    throw new BaseException("获取交货点信息失败");
                }
            }

            OrderLocation orderLocation = new OrderLocation();
            // 订单 id
            orderLocation.setOrderId(order.getId());
            // 发货点编码
            orderLocation.setShippingLocationId(startLocation.getId());
            // 交货点编码
            orderLocation.setDeliveryLocationId(endLocation.getId());
            // 创建时间
            orderLocation.setGmtCreate(new Date());
            orderLocation.setTenantId(teanantId);
            // 订单各类地址信息
            orderLocationService.insert(orderLocation);
            OmsOrderLocation ool = new OmsOrderLocation();
            BeanUtils.copyProperties(orderLocation, ool);

            order.setOrderLocation(orderLocation);

            List<OrderItem> orderItems = Lists.newArrayList();
            List<OmsOrderItem> oois = Lists.newArrayList();
            for (ShipLineInfoBO shipLineInfoBO : generateOrderBO.getShipLineInfoBOList()) {
                //插入订单ITEM
                OrderItem orderItem = new OrderItem();
                // 订单 id
                orderItem.setOrderId(order.getId());
                // 数量
                orderItem.setAmount(1);
                // 度量单位
                orderItem.setUom("辆");
                // 所下订单中的原始货物标识信息(客户系统推送或录单人录入)
                if (!StringUtils.isEmpty(shipLineInfoBO.getVcvin()) && !"null".equals(shipLineInfoBO.getVcvin())) {
                    orderItem.setIssueItemId(shipLineInfoBO.getVcvin());
                }
                if (!StringUtils.isEmpty(shipLineInfoBO.getVcstyleno()) && !"null".equals(shipLineInfoBO.getVcstyleno())) {
                    orderItem.setMaterial(shipLineInfoBO.getVcstyleno());
                }

                orderItem.setTenantId(teanantId);
                // 创建时间
//                orderItem.setGmtCreate(new Date());
                orderItems.add(orderItem);
                orderItemService.insert(orderItem);
                OmsOrderItem ooi = new OmsOrderItem();
                BeanUtils.copyProperties(orderItem, ooi);
                oois.add(ooi);
                // 保存订单订单明细

            }
            order.setOrderItemList(orderItems);
            OmsOrder omsOrder = new OmsOrder();
            BeanUtils.copyProperties(order, omsOrder);
            omsOrder.setOrderItemList(oois);
            omsOrder.setOrderLocation(ool);
            shipmentAutoDTO.addOrder(omsOrder);
        }

        shipmentAutoDTO.setTransportationId(shippingInfoBO.getVclicense());
        shipmentAutoDTO.setTenantId(teanantId);

        //下订单，自动生成TMS的运单、任务和装车单
        com.zhiche.lisa.tms.dto.ShipmentAutoDTO shipmentAuto = new com.zhiche.lisa.tms.dto.ShipmentAutoDTO();
        BeanUtils.copyProperties(shipmentAutoDTO, shipmentAuto);
        List<OrderAssignDTO> orderAssignList = iShipOrderService.autoShipment(shipmentAuto, authorization);
        // 回写下发单委托单号（下游系统回写单号）
        if (CollectionUtils.isNotEmpty(orderAssignList)) {
            for (OrderAssignDTO orderAssignDTO : orderAssignList) {
                OrderAssign orderAssign = new OrderAssign();
                BeanUtils.copyProperties(orderAssignDTO, orderAssign);
                orderAssign.setGmtAssign(new Date());
                orderAssign.setAssignLog("成功");
                orderAssign.setTenantId(teanantId);
                orderAssignService.insert(orderAssign);
            }
        }
        //fix  调整运力平台司机报班状态为已安排
        CarrierInfoLineVO infoLineVO = selectCarrierInfoByPlate(shippingInfoBO.getVclicense());
        LOGGER.info("erp指令--->根据车牌查询司机信息result:{}", JSONObject.toJSONString(infoLineVO));
        if (infoLineVO != null
                && StringUtils.isNotBlank(shippingInfoBO.getCheckinId())) {
            List<NameValuePair> headNamePairs = Lists.newArrayList();
            headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
            // 连接lspm 将司机报班状态调整为已安排--
            headNamePairs.add(new BasicNameValuePair("checkInType", "IU"));
            String result = HttpClientUtil.get(getDriverInfoById + "/" + infoLineVO.getDriverId() + "/" + shippingInfoBO.getCheckinId(), headNamePairs, null, socketTimeout);
            LOGGER.info("指令新增 连接LSPM 调整司机报班状态:url:{},result:{}", getDriverInfoById + "/" + infoLineVO.getDriverId() + "/" + shippingInfoBO.getCheckinId(), result);
        } else {
            LOGGER.info("指令号:{},报班id:{},infoLineVO:{}", shippingInfoBO.getVcshipno(), shippingInfoBO.getCheckinId(), infoLineVO);
        }
    }

    ///**
    // * 发运时查询OMS 订单获取指令信息
    // */
    //@Override
    //public Order queryOrder(Map<String, String> condition) {
    //    if (condition != null && !condition.isEmpty()) {
    //        EntityWrapper<OrderAssign> ew = new EntityWrapper<>();
    //        String toc = condition.get("tmsOrderCode");
    //        if (StringUtils.isBlank(toc)) {
    //            throw new BaseException("msOrderCode 不能为空");
    //        }
    //        ew.eq("consign_code", toc)
    //                .eq("is_delete", TableStatusEnum.STATUS_0.getCode())
    //                .orderBy("id", false);
    //        OrderAssign assign = orderAssignService.selectOne(ew);
    //        if (assign == null) {
    //            throw new BaseException("未查询到tmsOrderCode:" + toc + "的下发订单信息");
    //        }
    //        EntityWrapper<Order> oew = new EntityWrapper<>();
    //        oew.eq("code", assign.getOrderCode())
    //                .eq("is_delete", TableStatusEnum.STATUS_0.getCode())
    //                .orderBy("id", false);
    //        Order order = selectOne(oew);
    //        if (order == null) {
    //            throw new BaseException("未查询到omsOrderCode:" + assign.getOrderCode() + "的订单信息");
    //        }
    //        return order;
    //    }
    //    return null;
    //}

    /**
     * 根据id查询订单信息
     *
     * @param id
     */
    @Override
    public Order queryOrderById(Long id) {
        Order cn = null;
        Wrapper<Order> ew = new EntityWrapper<>();
        if (id != null) {
            ew.eq("id", id);
            cn = this.selectOne(ew);
        }
        return cn;
    }


    /**
     * 调用接口获取调度指令
     */
    private ShippingInfoBO getNewestShipByERP(String license) {
        ShippingInfoBO shippingInfoBO = null;

        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", ""));
        List<NameValuePair> params = Lists.newArrayList();
        params.add(new BasicNameValuePair("vclicense", license));
        LOGGER.info("定时任务获取ERP指令--->url:{},vclicense:{}", getNewestShipByLicenseUrl, license);
        String strReturn = HttpClientUtil.get(getNewestShipByLicenseUrl, headNamePairs, params, socketTimeout);
        if (!StringUtils.isEmpty(strReturn)) {
            RestfulResponse<ShippingInfoBO> restVO = JSON.parseObject(strReturn, new
                    TypeReference<RestfulResponse<ShippingInfoBO>>() {
                    });
            shippingInfoBO = restVO.getData();
        }
        return shippingInfoBO;
    }

//    private ShipOrder getShipOrderInfo(String authorization,Long itemId) {
//        ShipOrder shipOrder = null;
//        List<NameValuePair> headNamePairs = Lists.newArrayList();
//        headNamePairs.add(new BasicNameValuePair("Authorization",authorization));
//        List<NameValuePair> params = Lists.newArrayList();
//        params.add(new BasicNameValuePair("itemId", String.valueOf(itemId)));
//        String strReturn = HttpClientUtil.get(getShipOrderByItemIdURL,headNamePairs,params,socketTimeout);
//        if(!StringUtils.isEmpty(strReturn)){
//            RestfulResponse<ShipOrder> restVO = JSON.parseObject(strReturn, new TypeReference<RestfulResponse<ShipOrder>>(){});
//            shipOrder = restVO.getData();
//        }
//        return shipOrder;
//    }

//    public void generateShipOrder(String authorization,GenerateShipOrderBO generateShipOrderBO) {
//        List<NameValuePair> headNamePairs = Lists.newArrayList();
//        headNamePairs.add(new BasicNameValuePair("Authorization",authorization));
//        String strReturn = HttpClientUtil.postJson(generateShipOrder, headNamePairs, JSON.toJSONString(generateShipOrderBO), socketTimeout);
//        Integer code = null;
//        String message = null;
//        if(!StringUtils.isEmpty(strReturn)){
//            RestfulResponse<ShipOrder> restVO = JSON.parseObject(strReturn, new TypeReference<RestfulResponse<ShipOrder>>(){});
//            code = restVO.getCode();
//            message = restVO.getMessage();
//        }
//
//        if (StringUtils.isEmpty(strReturn) || code!=0) {
//            throw new BaseException("生成运单异常：" + message);
//        }
//    }

    private List<OrderAssign> autoShipment(String authorization, Object params, String url) {
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
        String strReturn = HttpClientUtil.postJson(url, headNamePairs,
                JSON.toJSONString(params), socketTimeout);
        if (!StringUtils.isEmpty(strReturn)) {
            RestfulResponse<List<OrderAssign>> restVO = JSON.parseObject(strReturn,
                    new TypeReference<RestfulResponse<List<OrderAssign>>>() {
                    });
            if (restVO.getCode() == 0) {
                return restVO.getData();
            } else {
                LOGGER.error("生成运单异常 url:{},message:{}", url, restVO.getMessage());
//                throw new BaseException("生成运单异常：" + restVO.getMessage());
            }

        } else {
            LOGGER.error("连接TMS异常" + url);
//            throw new BaseException("连接TMS异常");
        }
        return null;
    }


    /**
     * 得到租户应用管理员
     *
     * @return
     */
    private List<TechAccount> getToken() {
//        List<String> techAccountIdentifiers = Lists.newArrayList();
        String strReturn = HttpClientUtil.get(getTentUrl, null, 10000);
        RestfulResponse<List<TechAccount>> result = JSON.parseObject(strReturn,
                new TypeReference<RestfulResponse<List<TechAccount>>>() {
                });
        if (result.getCode() == 0) {
            return result.getData();
        } else {
            return null;
        }
//        JSONObject jsonObject = JSON.parseObject(strReturn);
//        int status = jsonObject.getInteger("code");
//        if(status == 0){
//            JSONArray jsonArray = jsonObject.getJSONArray("data");
//            if(CollectionUtils.isNotEmpty(jsonArray)){
//                jsonArray.forEach(object1 -> {
//                    JSONObject jsonObject1 = (JSONObject) object1;
//                    String techAccountIdentifier = jsonObject1.getString("techAccountIdentifier");
//                    techAccountIdentifiers.add(techAccountIdentifier);
//                });
//            }
//        }
//        return techAccountIdentifiers;
    }

    /**
     * * 生成订单
     *
     * @param authorization
     * @param plateList
     * @return
     */
    private Boolean generateOrder(String authorization, List<String> plateList, Long teanantId) {
        Boolean returnValue = false;
//        String licenses = StringUtils.join(plateList.toArray(), ",");
//        List<NameValuePair> headNamePairs = Lists.newArrayList();
//        headNamePairs.add(new BasicNameValuePair("Authorization",authorization));
//        Map<String, String> paramsMap = Maps.newHashMap();
//        paramsMap.put("licenses",licenses);

        createOrderByErpShipment(authorization, plateList, teanantId);


//        String strReturn = HttpClientUtil.post(generateOrderUrl,headNamePairs,paramsMap,socketTimeout);
//        if(!StringUtils.isEmpty(strReturn)){
//            RestfulResponse<Boolean> result = JSON.parseObject(strReturn, new TypeReference<RestfulResponse<Boolean>>(){});
//            returnValue = result.getData();
//        }
        return true;
    }

    private String getTenantToken(String techAccountIdentifier) {
        Map<String, String> parmers = Maps.newHashMap();
        parmers.put("username", techAccountIdentifier);
        parmers.put("password", "123456");
        parmers.put("client_id", getClinetId);
        parmers.put("client_secret", getClientSecret);
        parmers.put("grant_type", "password");
        String result = HttpClientUtil.post(getTokenUrl, parmers, socketTimeout);
        if (StringUtils.isEmpty(result)) return null;
        JSONObject jsonObject2 = JSON.parseObject(result);
        if (Objects.nonNull(jsonObject2)) {
            String access_token = jsonObject2.getString("access_token");
            String authorization = "Bearer " + access_token;
            return authorization;
        } else {
            return null;
        }
    }

    private List<String> getCarrierPlates(String token, Long tenantId) {
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", token));
        List<NameValuePair> params = Lists.newArrayList();
        params.add(new BasicNameValuePair("tenantId", tenantId.toString()));
        String strReturn = HttpClientUtil.get(authedCarrierPlateURL, headNamePairs, params, socketTimeout);
        if (!StringUtils.isEmpty(strReturn)) {
            RestfulResponse<List<String>> restVO = JSON.parseObject(strReturn, new TypeReference<RestfulResponse<List<String>>>() {
            });
            List<String> plateList = restVO.getData();
            if (!CollectionUtils.isEmpty(plateList)) {
                LOGGER.info(plateList.size() + "条已经认证的牵引车车牌 ====================");
            } else {
                LOGGER.info("不存在已经认证的牵引车车牌 ====================");
            }
            return plateList;
        } else {
            return null;
        }

    }

    private GenerateOrderBO getGenerateOrderBO(ShipLineInfoBO shipLineInfoBO, List<GenerateOrderBO> generateOrderBOList) {
        for (GenerateOrderBO generateOrderBO : generateOrderBOList) {
            if (shipLineInfoBO.getIstartcityid().equals(generateOrderBO.getIstartcityid())
                    && shipLineInfoBO.getIendcityid().equals(generateOrderBO.getIendcityid())) {
                return generateOrderBO;
            }
        }
        GenerateOrderBO generateOrderBO = new GenerateOrderBO();
        BeanUtils.copyProperties(shipLineInfoBO, generateOrderBO);
        generateOrderBOList.add(generateOrderBO);
        return generateOrderBO;
    }

    @Override
    public Boolean loginWithOutToken(ShipmentInfoVO shipmentInfoVO) {
        CarrierInfoLineVO carrierInfoLineVO = selectCarrierInfoByPlate(shipmentInfoVO.getPlateNo());
        String authorization = tokenUtil.getTenantToken("tech-" + carrierInfoLineVO.getTenantId());
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
        HttpClientUtil.postJson("http://localhost:8090/order/createOrder", headNamePairs, JSONObject.toJSONString(shipmentInfoVO), 100000);
        return true;
    }

    /**
     * 同步数据添加订单信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addOrder(ShipmentInfoVO shipmentInfoVO, String authorization) {
        //不处理下发给慧运车的指令
        if (TableStatusEnum.STATUS_HUIYUNCHE_51.getCode().equals(shipmentInfoVO.getServiceProviderId())) {
            LOGGER.info("下发给慧运车的指令: {},承运商名称:{}", shipmentInfoVO.getShipmentId(), shipmentInfoVO.getServiceProviderName());
            throw new BaseException("不处理下发给慧运车的指令：" + shipmentInfoVO.getShipmentId() + shipmentInfoVO.getServiceProviderName());
//            return;
        }
        if ("194".equals(shipmentInfoVO.getFleetId())) {
            LOGGER.info("中铁干线段的指令: {},承运商名称:{}", shipmentInfoVO.getShipmentId(), shipmentInfoVO.getServiceProviderName());
            throw new BaseException("不处理中铁"+shipmentInfoVO.getShipmentType()+"的指令：" + shipmentInfoVO.getShipmentId() + shipmentInfoVO.getServiceProviderName());
//            return;
        }
        if ("312".equals(shipmentInfoVO.getFleetId()) || TableStatusEnum.STATUS_FLEET.getCode().equals(shipmentInfoVO.getFleetId())){
            LOGGER.info("中联提车队的指令: {},承运商名称:{}", shipmentInfoVO.getShipmentId(), shipmentInfoVO.getServiceProviderName());
            throw new BaseException("不处理中联提车队"+shipmentInfoVO.getShipmentType()+"的指令：" + shipmentInfoVO.getShipmentId() + shipmentInfoVO.getServiceProviderName());
        }
        //if (StringUtils.isNotBlank(authorization)) {
        CarrierInfoLineVO carrierInfoLineVO = null;
        if (StringUtils.isNotBlank(shipmentInfoVO.getPlateNo())) {
            //正常牵引车下发指令
            carrierInfoLineVO = selectCarrierInfoByPlate(shipmentInfoVO.getPlateNo());
        }
        if (carrierInfoLineVO == null
                && StringUtils.isNotBlank(shipmentInfoVO.getServiceProviderId())) {
            //针对魏军车队做为供方,司机/车牌接收指令  便于B->C结算
            carrierInfoLineVO = queryFleetBasicWithId(shipmentInfoVO.getFleetId(), authorization);
        }

        //authorization = tokenUtil.getTenantToken("tech-" + carrierInfoLineVO.getTenantId());
        //String token = StringUtils.substringAfter(authorization, "Bearer ");
        //JwtAccountVO accountVO = JwtTokenUtil.decodeJwt(token);
        if (TableStatusEnum.STATUS_FLEET.getDetail().equals(carrierInfoLineVO.getFleetName())) {
            //不处理下发中联提车队的指令
            LOGGER.info("中联提车队的指令: {},车队名:{}", shipmentInfoVO.getShipmentId(), carrierInfoLineVO.getFleetName());
            throw new BaseException("不处理中联提车队的指令：" + shipmentInfoVO.getShipmentId() + carrierInfoLineVO.getFleetName());
//            return;
        }
        shipmentInfoVO.setTenantId(Long.valueOf(carrierInfoLineVO.getTenantId()));
        shipmentInfoVO.setCreator("unlcn");
        if (carrierInfoLineVO != null
                && Objects.nonNull(carrierInfoLineVO.getLspId())
                && StringUtils.isNotEmpty(carrierInfoLineVO.getLspName())) {
            if (StringUtils.isEmpty(shipmentInfoVO.getTransactionCode())) {
                throw new BaseException("数据处理方式为空");
            }
            // 根据明细生成的订单数
            List<ShipmentInfoVO> shipmentInfoVOS = new ArrayList<>();
            // 组装头和明细关系
            if (CollectionUtils.isNotEmpty(shipmentInfoVO.getShipTaskDTOList())) {
                for (OrderVO orderVO : shipmentInfoVO.getShipTaskDTOList()) {
                    ShipmentInfoVO shipmentInfoVO1 = getGenerateOrder(orderVO, shipmentInfoVOS);
                    shipmentInfoVO1.addOrderVO(orderVO);
                }
            } else {
                // 明细为空,走删除逻辑
                deleteOrder(shipmentInfoVO, authorization);
                orderToErp(shipmentInfoVO, authorization);
                return;
            }
            switch (shipmentInfoVO.getTransactionCode()) {
                case "IU":
                    insertOrder(shipmentInfoVOS, shipmentInfoVO, authorization);
                    break;
                case "R":
                    //updateOrder(shipmentInfoVO, authorization);
                    //fix 多种情况修改-先删除再新增
                    shipmentInfoVO.setTransactionCode("RC");
                    deleteOrder(shipmentInfoVO, authorization);
                    //整个新增
                    shipmentInfoVO.setTransactionCode("IU");
                    insertOrder(shipmentInfoVOS, shipmentInfoVO,authorization);
                    shipmentInfoVO.setTransactionCode("R");
                    break;
                default:
                    deleteOrder(shipmentInfoVO, authorization);
                    break;
            }
            if (StringUtils.isNotBlank(shipmentInfoVO.getPlateNo())) {
                orderToErp(shipmentInfoVO, authorization);
            }
        }
        // }

    }


    private CarrierInfoLineVO queryFleetBasicWithId(String fleetId, String token) {
        CarrierInfoLineVO carrierInfoLineVO = null;
//        List<NameValuePair> headNamePairs = Lists.newArrayList();
//        headNamePairs.add(new BasicNameValuePair("Authorization", token));
        Map<String, Object> params = new LinkedHashMap<>();
        params.put("fleetId", fleetId);
        String jsonParam = JSONObject.toJSONString(params);
        LOGGER.info("tms-->lspm 获取车队信息 url:{},param:{}", queryFleetBasic, jsonParam);
        String strReturn = null;
        try {
            strReturn = HttpClientUtil.postJson(queryFleetBasic, null, jsonParam, socketTimeout);
            LOGGER.info("tms-->lspm 获取车队信息 param:{},result:{}", jsonParam, strReturn);
            if (StringUtils.isNotBlank(strReturn)) {
                carrierInfoLineVO = new CarrierInfoLineVO();
                JSONObject ro = JSONObject.parseObject(strReturn);
                //返回成功
                if (StringUtils.isNotBlank(ro.getString("code"))
                        && TableStatusEnum.STATUS_0.getCode().equals(ro.getString("code"))) {
                    String data = ro.getString("data");
                    JSONObject dataOb = JSONObject.parseObject(data);
                    if (dataOb != null) {
                        carrierInfoLineVO.setLspId(Long.valueOf(dataOb.getString("lspId")));
                        carrierInfoLineVO.setLspName(dataOb.getString("lspName"));
                        carrierInfoLineVO.setFleetId(Long.valueOf(fleetId));
                        carrierInfoLineVO.setFleetName(dataOb.getString("fleetName"));
                        carrierInfoLineVO.setTenantId(dataOb.getString("tenantId"));
                    }else {
                        throw new BaseException("根据车队Id获取车队信息失败");
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.info("tms-->lspm 获取车队信息 失败: url:{},param:{},error:{}", getCarrierInfoByPlate, jsonParam, e);
            throw new BaseException("根据车队Id("+fleetId+")获取车队信息失败");
        }
        return carrierInfoLineVO;
    }

    /**
     * 中联创建的自有车队推送到erp
     */
    public void orderToErp(ShipmentInfoVO shipmentInfoVO, String authorization) {
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
        LOGGER.info("result (判断司机是否是中联自有车队请求参数) url:{},param:{}", isUnlcnFleetDriverUrl, shipmentInfoVO.getDriverId());
        String result = HttpClientUtil.get(isUnlcnFleetDriverUrl + "/" + shipmentInfoVO.getDriverId(), headNamePairs, null, socketTimeout);
        LOGGER.info("result (判断司机是否是中联自有车队返回结果) url:{},erpResult:{}", isUnlcnFleetDriverUrl + "/" + shipmentInfoVO.getDriverId(), result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String data = jsonObject.getString("data");
        if (!StringUtils.isEmpty(data)) {
            DriverVO driverVO = JSONObject.parseObject(data, DriverVO.class);
            shipmentInfoVO.setDriverMoble(driverVO.getMobile());
            shipmentInfoVO.setServiceProviderName(driverVO.getFleetName());
            shipmentInfoVO.setDriverName(driverVO.getName());
            //设置自有车队调度时间 字段 gmt_modified
            setOtmShipmentModifiedDate(shipmentInfoVO);
            //shipmentInfoVO.setGmtModified(new Date());
            if (shipmentInfoVO.getTransactionCode().equals("RC")) {
                shipmentInfoVO.setTotalShipCount(0);
            }
            //转换业务主体
            // fix 业务主体由ils确认 并下发
            //List<OrderVO> taskDTOList = shipmentInfoVO.getShipTaskDTOList();
            //if (CollectionUtils.isNotEmpty(taskDTOList)) {
            //    taskDTOList.forEach(v -> {
            //        getCiamsId(headNamePairs, v);
            //    });
            //}
            //转换承运商-->车队id
            shipmentInfoVO.setServiceProviderId(String.valueOf(driverVO.getFleetId()));
            String jsonStr = JSONObject.toJSONString(shipmentInfoVO);
            //fix  增加推送ERP日志记录
            TmsExplogLine explogLine = new TmsExplogLine();
            explogLine.setExportType(InterfaceEventEnum.BS_CREATED.getCode());
            explogLine.setExportKey(shipmentInfoVO.getShipmentId());
            explogLine.setTargetSys("ERP");
            explogLine.setInterfaceUrl(rmtILSShipUrl);
            explogLine.setDataContent(jsonStr);
            explogLine.setGmtCreate(new Date());
            explogLine.setRemarks("自有车队指令推送ERP");
            new Thread(() -> {
                try {
                    LOGGER.info("自有车队指令推送ERP---> url:{},params:{}", rmtILSShipUrl, jsonStr);
                    String erpResult = HttpClientUtil.postJson(rmtILSShipUrl, headNamePairs, jsonStr, socketTimeout);
                    LOGGER.info("自有车队指令推送ERP结果---> url:{},plateNo:{},erpResult:{}", rmtILSShipUrl, shipmentInfoVO.getPlateNo(), erpResult);
                    explogLine.setExportStatus(TableStatusEnum.STATUS_Y.getCode());
                    explogLine.setExportResponse(erpResult);
                } catch (Exception e) {
                    LOGGER.error("调度指令连接erp失败 error{}", e);
                    explogLine.setExportStatus(TableStatusEnum.STATUS_N.getCode());
                }
                explogLineService.insert(explogLine);
            }).start();
        }

    }

    /**
     * 拿取OTMShipment创建时间设置指令调度时间
     */
    private void setOtmShipmentModifiedDate(ShipmentInfoVO shipmentInfoVO) {
        if (Objects.isNull(shipmentInfoVO.getInsertDate())) {
            EntityWrapper<ImportLogHistory> OtmShipmentEW = new EntityWrapper<>();
            OtmShipmentEW.eq("source_key", shipmentInfoVO.getShipmentId())
                    .eq("source_sys", "otm")
                    .orderBy("id", false);
            List<ImportLogHistory> importLogHistories = importLogHistoryService.selectListNoTenant(OtmShipmentEW);
            if (CollectionUtils.isNotEmpty(importLogHistories)) {
                ImportLogHistory logHistory = importLogHistories.get(0);
                shipmentInfoVO.setGmtModified(logHistory.getGmtCreate());
            }
        }else{
            shipmentInfoVO.setGmtModified(shipmentInfoVO.getInsertDate());
        }
    }

    /**
     * 查询ERP 自有车队的业务主体
     */
    private void getCiamsId(List<NameValuePair> headNamePairs, OrderVO v) {
        HashMap<String, String> param = Maps.newHashMap();
        param.put("corpName", v.getCustomerId());
        String requestParam = JSONObject.toJSONString(param);
        LOGGER.info("请求integration获取业务主体 url:{},param:{}", integrationUrl + queryCiamsNameList, requestParam);
        String corpRes = HttpClientUtil.postJson(integrationUrl + queryCiamsNameList, headNamePairs, requestParam, socketTimeout);
        JSONObject object = JSONObject.parseObject(corpRes);
        String resData = object.getString("data");
        if (StringUtils.isNotBlank(resData)) {
            List<Map> list = JSONObject.parseArray(resData, Map.class);
            if (CollectionUtils.isNotEmpty(list)) {
                Map map = list.get(0);
                Object id = map.get("id");
                if (id != null) {
                    v.setCiamsId(id.toString());
                }
            }

        }
    }

    /**
     * 添加订单
     */
    private void insertOrder(List<ShipmentInfoVO> shipmentInfoVOList,
                             ShipmentInfoVO shipmentInfoVO,
                             String authorization) {
        //当前登录用户租户id
        Long teanantId = shipmentInfoVO.getTenantId();
        ShipmentOrderDTO shipmentOrderDTO = new ShipmentOrderDTO();
        BeanUtils.copyProperties(shipmentInfoVO, shipmentOrderDTO);
        //获取运输方式id
        Long transTypeId = getTransTypeId(shipmentInfoVO.getTransportModeId());
        if (null == transTypeId) {
            LOGGER.error("未查询到对应的运输方式 error:{}", shipmentInfoVO.getTransportModeId());
        }
        EntityWrapper<Order> wrapper = new EntityWrapper<>();
        wrapper.eq("customer_order_id", shipmentInfoVO.getShipmentId()).eq("is_delete", TableStatusEnum.STATUS_0.getCode());
        if (this.selectCountNotenant(wrapper) > 0) {
            LOGGER.error("指令号:{}", shipmentInfoVO.getShipmentId() + "已存在");
            throw new BaseException("指令号:" + shipmentInfoVO.getShipmentId() + "已存在");
        }
        for (ShipmentInfoVO shipmentInfo : shipmentInfoVOList) {//生成订单
            Order order = new Order();
            order.setCode("CO" + snowFlakeId.nextId());
            order.setComment(shipmentInfo.getRemarks());
            order.setTos("fleet");
            order.setGmtIssue(new Date());
            order.setGmtCreate(new Date());
            order.setCustomerOrderId(shipmentInfo.getShipmentId());
            order.setTransTypeId(transTypeId);
            order.setTenantId(teanantId);
            order.setCurrentStatus(shipmentInfo.getStatus());
            order.setCustomerId("unlcn");
            order.setCustomerName("中联物流");
            this.insert(order);
            shipmentInfo.setOrderCode(order.getCode());
            //创建订单联系人 -调整报班状态
            OrderContact orderContact = addOrderContact(shipmentInfoVO, authorization, teanantId, order);
            order.setOrderContact(orderContact);
            List<LocationVo> locationVoList = new ArrayList<>();
            LocationVo endLocation = endLocation(shipmentInfo, teanantId, authorization);
            if (endLocation == null) {
                LOGGER.error("获取交货点信息失败");
                throw new BaseException("获取交货点信息失败");
            }
            shipmentInfoVO.setEndLocation(endLocation);
            locationVoList.add(endLocation);
            LocationVo startLocation = startLocation(shipmentInfo, teanantId, authorization);
            if (startLocation == null) {
                LOGGER.error("获取发货点信息失败");
                throw new BaseException("获取发货点信息失败");
            }
            shipmentInfoVO.setStartLocation(startLocation);
            locationVoList.add(startLocation);
            order.setLocation(locationVoList);
            //订单地址
            OrderLocation orderLocation = new OrderLocation();
            orderLocation.setOrderId(order.getId());
            orderLocation.setShippingLocationId(startLocation.getId());
            orderLocation.setDeliveryLocationId(endLocation.getId());
            orderLocation.setGmtCreate(new Date());
            orderLocation.setTenantId(teanantId);
            orderLocationService.insert(orderLocation);
            order.setOrderLocation(orderLocation);
            //插入订单ITEM
            List<OrderItem> orderItems = Lists.newArrayList();
            for (OrderVO orderVO : shipmentInfo.getShipTaskDTOList()) {
                OrderItem orderItem = new OrderItem();
                orderItem.setOrderId(order.getId());
                orderItem.setAmount(1);
                orderItem.setUom("辆");
                orderItem.setIssueItemId(orderVO.getVin());
                orderItem.setMaterial(orderVO.getStanVehicleType());
                orderItem.setTenantId(teanantId);
                orderItem.setGmtCreate(new Date());
                orderItem.setOwnerName(orderVO.getCustomerId());
                orderItem.setItemSourceKey(orderVO.getTaskId());
                orderItemService.insert(orderItem);
                orderItem.setCiamsId(orderVO.getCiamsId());
                orderItem.setIsTerminal(orderVO.getIsTerminal());
                orderItem.setCusWaybillId(orderVO.getCusWaybillNo());
                orderItem.setOrderDate(orderVO.getOrderDate());
                orderItem.setOrderNo(orderVO.getOrderNo());
                orderItems.add(orderItem);
                order.setDestLocationSequence(orderVO.getDestLocationSequence());
                order.setOriginLocationSequence(orderVO.getOriginLocationSequence());
                //insertPriceIncoming(shipmentInfoVO, order, orderVO, orderItem, transTypeId, authorization);
            }
            order.setOrderItemList(orderItems);
            shipmentInfo.setPlateNo(shipmentInfoVO.getPlateNo());
            shipmentInfo.setTransactionCode(shipmentInfoVO.getTransactionCode());
            shipmentOrderDTO.setTransportModeId(transTypeId == null ? null : String.valueOf(transTypeId));
            shipmentOrderDTO.addOrder(order);
            shipmentOrderDTO.setTenantId(shipmentInfoVO.getTenantId());
        }
        //下订单，自动生成TMS的运单、任务和装车单
        List<OrderAssignDTO> orderAssignList = iShipOrderService.addShipment(shipmentOrderDTO, authorization);
        // 回写下发单委托单号（下游系统回写单号）
        if (CollectionUtils.isNotEmpty(orderAssignList)) {
            for (OrderAssignDTO orderAssignDTO : orderAssignList) {
                OrderAssign orderAssign = new OrderAssign();
                BeanUtils.copyProperties(orderAssignDTO, orderAssign);
                orderAssign.setGmtAssign(new Date());
                orderAssign.setAssignLog("成功");
                orderAssign.setTenantId(teanantId);
                orderAssignService.insert(orderAssign);
            }
        }
    }

    private OrderContact addOrderContact(ShipmentInfoVO shipmentInfoVO, String authorization, Long teanantId, Order
            order) {
        OrderContact orderContact = new OrderContact();
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
        // 连接lspm 将司机报班状态调整为已安排--
        if (StringUtils.isNotBlank(shipmentInfoVO.getDriverId())) {
            headNamePairs.add(new BasicNameValuePair("checkInType", "IU"));
            LOGGER.info("指令新增 连接LSPM 调整司机报班状态:url{},driverId:{},checkinId:{}", getDriverInfoById, shipmentInfoVO.getDriverId(), shipmentInfoVO.getCheckinId());
            String result = HttpClientUtil.get(getDriverInfoById + "/" + shipmentInfoVO.getDriverId() + "/" + shipmentInfoVO.getCheckinId(), headNamePairs, null, socketTimeout);
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (jsonObject != null
                    && jsonObject.getInteger("code") == 0) {
                orderContact.setContactsName(jsonObject.getJSONObject("data").getString("name"));
                orderContact.setContactsPhone(jsonObject.getJSONObject("data").getString("mobile"));
            }
        }
        orderContact.setOrderCode(order.getCode());
        orderContact.setTenantId(teanantId);
        orderContactService.insert(orderContact);
        return orderContact;
    }

    private OrderContact addOrderContactNew(CarrierInfoLineVO carrierInfoLineVO, Long teanantId, Order
            order, OrderContact orderContact) {

        orderContact.setOrderCode(order.getCode());
        orderContact.setContactsPhone(carrierInfoLineVO.getDriverMobile());
        orderContact.setContactsName(carrierInfoLineVO.getDriverName());
        orderContact.setTenantId(teanantId);
        orderContactService.insertOrUpdate(orderContact);
        return orderContact;
    }

    /**
     * 更新订单信息
     */
    private void updateOrder(ShipmentInfoVO shipmentInfoVO, String authorization) {
        ShipmentOrderDTO shipmentOrderDTO = new ShipmentOrderDTO();
        Order updateOrder = new Order();
        List<OrderItem> synTmsList = new ArrayList<>();
        HashMap<String, OrderItem> allOldItem = Maps.newHashMap();
        List<OrderItem> oldItems = orderItemService.orderItemListByCustomerOrderId(shipmentInfoVO.getShipmentId());

        //如果运力 不存在指令生成的订单走新增逻辑
        if (CollectionUtils.isEmpty(oldItems)) {
            shipmentInfoVO.setTransactionCode("IU");
            addOrder(shipmentInfoVO, authorization);
            return;
        } else {
            for (OrderItem oldItem : oldItems) {
                allOldItem.put(oldItem.getItemSourceKey(), oldItem);
            }
        }

        HashMap<String, OrderItem> existsItem = Maps.newHashMap();
        List<OrderLocation> orderLocations = getOrderLocations(oldItems);

        //查询新的和以前的订单明细是否已经存在,便于后续删除更改减掉的车;
        for (OrderVO orderVO : shipmentInfoVO.getShipTaskDTOList()) {
            for (OrderItem oldItem : oldItems) {
                if (oldItem.getItemSourceKey().equals(orderVO.getTaskId())) {
                    existsItem.put(oldItem.getItemSourceKey(), oldItem);
                }
            }
            // 以前orders 肯定存在,不然走新增逻辑
            Wrapper<OrderItem> orderItemWrapper = new EntityWrapper<>();
            orderItemWrapper.eq("item_source_key", orderVO.getTaskId())
                    .eq("is_delete", Integer.valueOf(TableStatusEnum.STATUS_0.getCode()));
            OrderItem orderItems = orderItemService.selectOne(orderItemWrapper);
            //查询订单下面是否有订单明细没有就添加订单有就更新订单明细
            if (Objects.isNull(orderItems)) {
                shipmentInfoVO.setDestLocationProvince(orderVO.getDestLocationProvince());
                shipmentInfoVO.setDestLocationCity(orderVO.getDestLocationCity());
                shipmentInfoVO.setDestLocationCounty(orderVO.getDestLocationCounty());
                shipmentInfoVO.setDestLocationName(orderVO.getDestLocationName());
                shipmentInfoVO.setDestLocationAddress(orderVO.getDestLocationAddress());
                LocationVo endLocation = endLocation(shipmentInfoVO, shipmentInfoVO.getTenantId(), authorization);
                if (endLocation == null) {
                    LOGGER.error("获取交货点信息失败");
                }
                shipmentInfoVO.setEndLocation(endLocation);
                shipmentInfoVO.setOriginLocationProvince(orderVO.getOriginLocationProvince());
                shipmentInfoVO.setOriginLocationCity(orderVO.getOriginLocationCity());
                shipmentInfoVO.setOriginLocationCounty(orderVO.getOriginLocationCounty());
                shipmentInfoVO.setOriginLocationAddress(orderVO.getOriginLocationAddress());
                shipmentInfoVO.setOriginLocationName(orderVO.getOriginLocationName());
                LocationVo startLocation = startLocation(shipmentInfoVO, shipmentInfoVO.getTenantId(), authorization);
                if (startLocation == null) {
                    LOGGER.error("获取发货点信息失败");
                }
                shipmentInfoVO.setStartLocation(startLocation);
                for (int i = 0; i < orderLocations.size(); i++) {
                    OrderLocation location = orderLocations.get(i);
                    if (location.getShippingLocationName()
                            .equals(orderVO.getDestLocationProvince() + orderVO.getDestLocationCity() + orderVO.getDestLocationCounty())
                            && location.getDeliveryLocationName()
                            .equals(orderVO.getOriginLocationProvince() + orderVO.getOriginLocationCity() + orderVO.getOriginLocationCounty())) {
                        OrderItem orderItem = new OrderItem();
                        orderItem.setOrderId(location.getOrderId());
                        orderItem.setAmount(1);
                        orderItem.setUom("辆");
                        orderItem.setIssueItemId(orderVO.getVin());
                        orderItem.setMaterial(orderVO.getStanVehicleType());
                        orderItem.setTenantId(shipmentInfoVO.getTenantId());
                        orderItem.setGmtCreate(new Date());
                        orderItem.setOwnerName(orderVO.getCustomerId());
                        orderItem.setItemSourceKey(orderVO.getTaskId());
                        orderItemService.insert(orderItem);
                        //需同步tms 数据
                        synTmsList.add(orderItem);
                        //获取原order
                        Order order = selectById(location.getOrderId());
                        Long transTypeId = getTransTypeId(shipmentInfoVO.getTransportModeId());
                        if (null == transTypeId) {
                            LOGGER.error("未查询到对应的运输方式 error:{}", shipmentInfoVO.getTransportModeId());
                        }
                        //insertPriceIncoming(shipmentInfoVO, order, orderVO, orderItem, transTypeId, authorization);
                        break;
                    } else if (i == orderLocations.size() - 1) {
                        //循环到最后没匹配的订单起始地目的地
                        shipmentInfoVO.setTransactionCode("IU");
                        shipmentInfoVO.setIsUpdate(TableStatusEnum.STATUS_1.getCode());
                        //查询order 便于后续查询装车单.
                        Wrapper<Order> orderWrapper = new EntityWrapper<>();
                        orderWrapper.eq("customer_order_id", shipmentInfoVO.getShipmentId())
                                .orderBy("id", false);
                        Order order = selectOne(orderWrapper);
                        EntityWrapper<OrderAssign> orWrapper = new EntityWrapper<>();
                        orWrapper.eq("order_code", order.getCode())
                                .orderBy("id", false);
                        OrderAssign assign = orderAssignService.selectOne(orWrapper);
                        shipmentInfoVO.setShipOrderCode(assign.getConsignCode());
                        ArrayList<OrderVO> list = Lists.newArrayList();
                        list.add(orderVO);
                        shipmentInfoVO.setShipTaskDTOList(list);
                        shipmentInfoVO.setOriginLocationId(orderVO.getOriginLocationId());
                        shipmentInfoVO.setDestLocationId(orderVO.getDestLocationId());
                        //内部已同步TMS 生成运单
                        addOrder(shipmentInfoVO, authorization);
                    }
                }
            }
        }
        // 根据索引移除新指令和以前存在的数据
        if (!existsItem.isEmpty()) {
            existsItem.forEach((key, value) -> {
                allOldItem.remove(key);
            });
        }

        //剩下以前多出的明细(新减少的车)
        if (!allOldItem.isEmpty()) {
            allOldItem.forEach((key, orderItem) -> {
                orderItem.setIsDelete(1);
                orderItemService.updateById(orderItem);
                // 需同步TMS 数据
                synTmsList.add(orderItem);

                Order order = this.selectById(orderItem.getOrderId());
                Wrapper<OrderItem> orderItemWrapper = new EntityWrapper<>();
                orderItemWrapper.eq("order_id", order.getId())
                        .eq("is_delete", 0);
                int count = orderItemService.selectCount(orderItemWrapper);
                if (count == 0) {
                    order.setIsDelete(1);
                    this.updateById(order);
                    deletePriceIncoming(order.getCode(), authorization, shipmentInfoVO);
                } else {
                    deletePriceItem(order.getCode(), authorization, shipmentInfoVO, orderItem);
                }
            });

        }
        updateOrder.setOrderItemList(synTmsList);
        shipmentOrderDTO.addOrder(updateOrder);
        shipmentOrderDTO.setTransactionCode("R");
        //查询order 便于后续查询装车单
        Wrapper<Order> orderWrapper = new EntityWrapper<>();
        orderWrapper.eq("customer_order_id", shipmentInfoVO.getShipmentId())
                .orderBy("id", false);
        Order order = selectOne(orderWrapper);
        EntityWrapper<OrderAssign> orWrapper = new EntityWrapper<>();
        orWrapper.eq("order_code", order.getCode())
                .orderBy("id", false);
        OrderAssign assign = orderAssignService.selectOne(orWrapper);
        shipmentOrderDTO.setShipOrderCode(assign.getConsignCode());
        //同个更新tms运单数据
        //下订单，自动生成TMS的运单、任务和装车单
        shipmentOrderDTO.setServiceProviderId(shipmentInfoVO.getServiceProviderId());
        iShipOrderService.addShipment(shipmentOrderDTO, authorization);
    }

    /**
     * 获取 已经存在起始地和目的地
     */
    private List<OrderLocation> getOrderLocations(List<OrderItem> oldItems) {
        List<OrderLocation> orderLocations = new ArrayList<>();
        for (OrderItem oldItem : oldItems) {
            if (!Objects.isNull(oldItem)) {
                Wrapper<OrderLocation> orderLocationWrapper = new EntityWrapper<>();
                orderLocationWrapper.eq("order_id", oldItem.getOrderId());
                OrderLocation orderLocation = orderLocationService.selectOne(orderLocationWrapper);
                Wrapper<Location> shippingLocationWrapper = new EntityWrapper<>();
                shippingLocationWrapper.eq("id", orderLocation.getShippingLocationId());
                Location shippingLocation = locationService.selectOne(shippingLocationWrapper);
                orderLocation.setShippingLocationName(shippingLocation.getValue());
                Wrapper<Location> deliveryLocationWrapper = new EntityWrapper<>();
                deliveryLocationWrapper.eq("id", orderLocation.getDeliveryLocationId());
                Location deliveryLocation = locationService.selectOne(deliveryLocationWrapper);
                orderLocation.setDeliveryLocationName(deliveryLocation.getValue());
                orderLocation.setOrderId(oldItem.getOrderId());
                orderLocations.add(orderLocation);
            }
        }
        return orderLocations;
    }

    /**
     * 同步数据删除订单信息
     */
    private Boolean deleteOrder(ShipmentInfoVO shipmentInfoVO, String authorization) {
        ShipmentOrderDTO shipmentOrderDTO = new ShipmentOrderDTO();
        Wrapper<Order> orderWrapper = new EntityWrapper<>();
        orderWrapper.eq("customer_order_id", shipmentInfoVO.getShipmentId())
                .eq("is_delete", "0");
        List<Order> orders = this.selectList(orderWrapper);
        for (Order order : orders) {
            order.setIsDelete(1);
            this.updateById(order);
            Wrapper<OrderAssign> orderAssignWrapper = new EntityWrapper<>();
            orderAssignWrapper.eq("order_code", order.getCode());
            OrderAssign orderAssign = orderAssignService.selectOne(orderAssignWrapper);
            List<OrderAssign> orderAssigns = orderAssignService.selectList(orderAssignWrapper);
            for (OrderAssign updateOrderAssign : orderAssigns) {
                updateOrderAssign.setIsDelete(1);
                orderAssignService.updateById(updateOrderAssign);
            }
            Wrapper<OrderContact> orderContactWrapper = new EntityWrapper<>();
            orderContactWrapper.eq("order_code", order.getCode());
            OrderContact orderContact = new OrderContact();
            orderContact.setIsDelete(1);
            orderContactService.update(orderContact, orderContactWrapper);

            Wrapper<OrderItem> orderItemWrapper = new EntityWrapper<>();
            orderItemWrapper.eq("order_id", order.getId());
            OrderItem orderItem = new OrderItem();
            orderItem.setIsDelete(1);
            orderItemService.update(orderItem, orderItemWrapper);

            Wrapper<OrderLocation> orderLocationWrapper = new EntityWrapper<>();
            orderLocationWrapper.eq("order_id", order.getId());
            OrderLocation orderLocation = new OrderLocation();
            orderLocation.setIsDelete(1);
            orderLocationService.update(orderLocation, orderLocationWrapper);
            shipmentOrderDTO.setShipOrderCode(orderAssign.getConsignCode());
            shipmentOrderDTO.setTransactionCode("RC");
            //deletePriceIncoming(order.getCode(), authorization, shipmentInfoVO);
//             LOGGER.info("删除指令调用TMS --->url:{},param:{}", addShipmentURL, JSON.toJSONString(shipmentOrderDTO));
            //下订单，自动生成TMS的运单、任务和装车单
            shipmentOrderDTO.setServiceProviderId(shipmentInfoVO.getServiceProviderId());
            iShipOrderService.addShipment(shipmentOrderDTO, authorization);
        }
        // 增加删除调整司机报班状态-->已失效
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
        // 连接lspm 将司机报班状态调整为已安排--
        headNamePairs.add(new BasicNameValuePair("checkInType", "RC"));
        LOGGER.info("指令删除 连接LSPM 调整司机报班状态:url{},driverId:{},checkinId:{}", getDriverInfoById, shipmentInfoVO.getDriverId());
        HttpClientUtil.get(getDriverInfoById + "/" + shipmentInfoVO.getDriverId() + "/" + shipmentInfoVO.getCheckinId(), headNamePairs, null, socketTimeout);
        return true;
    }

    /**
     * 根据订单明细从OMS获取应收账款信息
     */
    @Override
    public Map<String, LisaFeeReceivable> queryFeeReceivableOms(List<String> wayBillDtlIds) {
        Map<String, LisaFeeReceivable> map = Maps.newHashMap();
        if (!CollectionUtils.isEmpty(wayBillDtlIds)) {
            List<LisaFeeReceivable> lisaFeeReceivables = baseMapper.queryOrderNoTenant(wayBillDtlIds);
            for (LisaFeeReceivable lisaFeeReceivable : lisaFeeReceivables) {
                map.put(lisaFeeReceivable.getWaybillDtlId(), lisaFeeReceivable);
            }
        }
        return map;
    }

    /**
     * 为TMS提供接口,根据shipOrderCode 查询order及指令号
     */
    @Override
    public Order queryOrderFromTms(Map<String, String> params) {
        if (params != null) {
            EntityWrapper<OrderAssign> ew = new EntityWrapper<>();
            String tmsOrderCode = params.get("tmsOrderCode");
            if (StringUtils.isNotBlank(tmsOrderCode)) {
                ew.eq("consign_code", tmsOrderCode);
                ew.eq("is_delete", TableStatusEnum.STATUS_0.getCode());
                ew.orderBy("id", false);
                List<Order> orders = baseMapper.selectOneNoTenant(ew);
                if (CollectionUtils.isNotEmpty(orders)) {
                    return orders.get(0);
                }
            }
        }
        return null;
    }

    /**
     * 插入bms收入价格表
     */
    @Override
    public void insertPriceIncoming(ShipmentInfoVO shipmentInfo,
                                    Order order,
                                    OrderVO orderVO,
                                    OrderItem orderItem,
                                    Long serviceTypeId, String authorization) {
        LOGGER.info("连接BMS 获取收入暂估价--->param:{}", JSON.toJSONString(shipmentInfo));
        if (FourPeopleEnum.JST.getId().equals(shipmentInfo.getServiceProviderId())
                || FourPeopleEnum.JX.getId().equals(shipmentInfo.getServiceProviderId())
                || FourPeopleEnum.LYTD.getId().equals(shipmentInfo.getServiceProviderId())
                || FourPeopleEnum.YJ.getId().equals(shipmentInfo.getServiceProviderId())) {
            PriceIncomingDTO priceIncomingDTO = new PriceIncomingDTO();
            priceIncomingDTO.setTenantId(shipmentInfo.getTenantId());
            priceIncomingDTO.setOrderCode(order.getCode());
            priceIncomingDTO.setCreateFrom(TableStatusEnum.STATUS_10.getCode());//10-OTM，20-人送，30-其他
            priceIncomingDTO.setCustomerId("unlcn");
            priceIncomingDTO.setCustomerName("中联物流");
            priceIncomingDTO.setItemSourceKey(orderVO.getTaskId());
            priceIncomingDTO.setOrderItemId(orderItem.getId());
            Map<String, BigDecimal> priceAndMiles = priceAndMiles(orderVO.getTaskId(), authorization);
            if (priceAndMiles != null) {
                //暂估价
                priceIncomingDTO.setEstIncomingPrice(priceAndMiles.get("price"));
                //计价里程
                priceIncomingDTO.setMileage(priceAndMiles.get("miles"));
            }
            //车架号
            priceIncomingDTO.setItemUid(orderItem.getIssueItemId());
            LocationVo endLocation = shipmentInfo.getEndLocation();
            LocationVo startLocation = shipmentInfo.getStartLocation();
            priceIncomingDTO.setDepartLocationId(startLocation.getId());
            priceIncomingDTO.setDepartLocationAdCode(startLocation.getAdCode());
            priceIncomingDTO.setTransTypeId(serviceTypeId);
            priceIncomingDTO.setDepartAdressName(startLocation.getValue());
            priceIncomingDTO.setDestLocationId(endLocation.getId());
            priceIncomingDTO.setDestLocationAdCode(endLocation.getAdCode());
            priceIncomingDTO.setDepartAdressName(endLocation.getValue());
            //priceIncomingDTO.setCreator(Long.valueOf(shipmentInfo.getCreator()));
            priceIncomingDTO.setCreateFrom(TableStatusEnum.STATUS_10.getCode());//10 otm 20人送  30 其它
            List<NameValuePair> headNamePairs = Lists.newArrayList();
            headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
            try {
                LOGGER.info("连接BMS 生成收入单据url:{},param:{}", insertPriceIncomingUrl, JSON.toJSONString(priceIncomingDTO));
                String result = HttpClientUtil.postJson(insertPriceIncomingUrl, headNamePairs, JSON.toJSONString(priceIncomingDTO), socketTimeout);
                LOGGER.error("连接BMS生成收入单据失败 result---->{}", result);
                if (StringUtils.isBlank(result)) {
                    interfaceCompensationService.interfaceCompensationData(JSON.toJSONString(priceIncomingDTO), "返回为空", FailureDataType.INCOME.getId(), authorization);
                }
            } catch (Exception e) {
                LOGGER.error("连接BMS生成收入单据失败 error:{}", e);
                interfaceCompensationService.interfaceCompensationData(JSON.toJSONString(priceIncomingDTO), "连接超时", FailureDataType.INCOME.getId(), authorization);
            }
        }
    }


    /**
     * 删除bms价格数据
     */
    private void deletePriceIncoming(String orderCode, String authorization, ShipmentInfoVO shipmentInfoVO) {
        LOGGER.info("deletePriceIncoming 删除指令调用BMS 判断四大家--->orderCode:{},shipmentInfoVO:{}", orderCode, JSON.toJSONString(shipmentInfoVO));
        if (FourPeopleEnum.JST.getId().equals(shipmentInfoVO.getServiceProviderId())
                || FourPeopleEnum.JX.getId().equals(shipmentInfoVO.getServiceProviderId())
                || FourPeopleEnum.LYTD.getId().equals(shipmentInfoVO.getServiceProviderId())
                || FourPeopleEnum.YJ.getId().equals(shipmentInfoVO.getServiceProviderId())) {
            PriceIncomingDTO priceIncomingDTO = new PriceIncomingDTO();
            priceIncomingDTO.setOrderCode(orderCode);
            priceIncomingDTO.setCreator(shipmentInfoVO.getTenantId());
            priceIncomingDTO.setCreateFrom(TableStatusEnum.STATUS_10.getCode());//10 otm 20人送  30 其它
            List<NameValuePair> headNamePairs = Lists.newArrayList();
            headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
            LOGGER.info("deletePriceIncoming 删除指令调用BMS 删除接口--->url:{},orderCode:{},shipmentInfoVO:{}", deletePriceIncomingUrl, orderCode, JSON.toJSONString(priceIncomingDTO));
            String strReturn = HttpClientUtil.postJson(deletePriceIncomingUrl, headNamePairs,
                    JSON.toJSONString(priceIncomingDTO), socketTimeout);
            LOGGER.info("deletePriceIncoming result {}", strReturn);
        }
    }

    /**
     * 更新bms价格表
     */
    private void deletePriceItem(String orderCode, String authorization, ShipmentInfoVO shipmentInfoVO, OrderItem
            orderItem) {
        LOGGER.info("deletePriceItem 删除指令调用BMS 判断四大家--->orderCode:{},shipmentInfoVO:{},orderItem:{}", orderCode, JSON.toJSONString(shipmentInfoVO), JSON.toJSONString(orderItem));
        if (FourPeopleEnum.JST.getId().equals(shipmentInfoVO.getServiceProviderId())
                || FourPeopleEnum.JX.getId().equals(shipmentInfoVO.getServiceProviderId())
                || FourPeopleEnum.LYTD.getId().equals(shipmentInfoVO.getServiceProviderId())
                || FourPeopleEnum.YJ.getId().equals(shipmentInfoVO.getServiceProviderId())) {
            PriceIncomingDTO priceIncomingDTO = new PriceIncomingDTO();
            priceIncomingDTO.setOrderCode(orderCode);
            priceIncomingDTO.setOrderItemId(orderItem.getId());
            priceIncomingDTO.setIsDelete(Integer.valueOf(TableStatusEnum.STATUS_1.getCode()));
            priceIncomingDTO.setCreateFrom(TableStatusEnum.STATUS_10.getCode());//10 otm 20人送  30 其它
            priceIncomingDTO.setCreator(shipmentInfoVO.getTenantId());
            List<NameValuePair> headNamePairs = Lists.newArrayList();
            headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
            LOGGER.info("deletePriceItem 删除指令调用BMS --->url:{},param:{}", updateIncomingPriceByTaskCodeUrl, JSON.toJSONString(priceIncomingDTO));
            String strReturn = HttpClientUtil.postJson(updateIncomingPriceByTaskCodeUrl, headNamePairs,
                    JSON.toJSONString(priceIncomingDTO), socketTimeout);
            LOGGER.info("deletePriceItem result {}", strReturn);
        }
    }


    private ShipmentInfoVO getGenerateOrder(OrderVO orderVO, List<ShipmentInfoVO> shipmentInfoVOList) {
        for (ShipmentInfoVO shipmentInfoVO : shipmentInfoVOList) {
            if (orderVO.getDestLocationId().equals(shipmentInfoVO.getDestLocationId())
                    && orderVO.getOriginLocationId().equals(shipmentInfoVO.getOriginLocationId())) {
                return shipmentInfoVO;
            }
        }
        ShipmentInfoVO shipmentInfoVO = new ShipmentInfoVO();
        BeanUtils.copyProperties(orderVO, shipmentInfoVO);
        shipmentInfoVOList.add(shipmentInfoVO);
        return shipmentInfoVO;

    }

    /**
     * 获取车.承运商.司机信息
     */
    private CarrierInfoLineVO selectCarrierInfoByPlate(String plate) {
        CarrierInfoLineVO carrierInfoLineVO = null;
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", null));
        List<NameValuePair> params = Lists.newArrayList();
        params.add(new BasicNameValuePair("plate", plate));
        LOGGER.info("tms-->lspm 获取牵引车及司机信息 url:{},param:{}", getCarrierInfoByPlate, plate);
        String strReturn = null;
        try {
            strReturn = HttpClientUtil.get(getCarrierInfoByPlate, headNamePairs, params, socketTimeout);
            LOGGER.info("tms-->lspm 获取牵引车及司机信息 param:{},result:{}", plate, strReturn);
            if (StringUtils.isNotBlank(strReturn)) {
                RestfulResponse<CarrierInfoLineVO> restfulResponse = JSON.parseObject(strReturn, new TypeReference<RestfulResponse<CarrierInfoLineVO>>() {
                });
                carrierInfoLineVO = restfulResponse.getData();
            }
        } catch (Exception e) {
            LOGGER.info("tms-->lspm 获取牵引车及司机信息 失败: url:{},param:{},error:{}", getCarrierInfoByPlate, plate, e);
            throw new BaseException("获取牵引车及司机信息:"+e.getMessage());
        }
        return carrierInfoLineVO;
    }

    /**
     * 获取价格跟里程
     */
    private Map<String, BigDecimal> priceAndMiles(String orderNo, String authorization) {
        Map<String, BigDecimal> result = new HashMap<>();
        Map<String, String> orderno = new HashMap<>();
        orderno.put("orderno", orderNo);
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
        String priceAndMiles = HttpClientUtil.postJson(integrationUrl + getPriceAndMilesUrl, headNamePairs,
                JSON.toJSONString(orderno), socketTimeout);
        LOGGER.info("priceAndMiles url:{},param:{}, result {}", integrationUrl + getPriceAndMilesUrl, JSON.toJSONString(orderno), priceAndMiles);
        if (StringUtils.isNotBlank(priceAndMiles)) {
            JSONObject parseObject = JSONObject.parseObject(priceAndMiles);
            if (parseObject.getIntValue("code") == 0) {
                //暂估价
                result.put("price", parseObject.getJSONObject("data").getBigDecimal("price"));
                //计价里程
                result.put("miles", parseObject.getJSONObject("data").getBigDecimal("miles"));
            } else {
                LOGGER.error("获取价格里程失败" + parseObject.getString("message"));
//                throw new BaseException("获取价格里程失败" + parseObject.getString("message"));
            }
        } else {
            LOGGER.error("连接OTM获取价格里程失败");
//            throw new BaseException("连接OTM获取价格里程失败");
        }

        return result;
    }

    /**
     * 获取运输方式id
     */
    @Override
    public Long getTransTypeId(String serviceTypeName) {
        //转换运输方式名称差异
        String typeName = getTrailerTypeName(serviceTypeName);
        List<TransportationTypeDTO> allTransType = mdmUtil.getAllTransType();
        if (CollectionUtils.isNotEmpty(allTransType)) {
            for (TransportationTypeDTO dto : allTransType) {
                if (dto.getValue().equals(typeName)) {
                    return dto.getId();
                }
            }
        }
        return null;
    }

    @Override
    public int selectCountNotenant(EntityWrapper<Order> orderEW) {
        return baseMapper.selectCountNotenant(orderEW);
    }

    @Override
    public Order selectOneNotenant(EntityWrapper<Order> ew) {
        return baseMapper.selectOneNotenant(ew);
    }

    @Override
    public void getErpDispatch(String plateNo, String authorization, String tenantId) {
        ShippingInfoBO shippingInfoBO = erpUtil.getNewestShipByERP(plateNo);
        if (!Objects.isNull(shippingInfoBO)) {
            Wrapper<Order> orderWrapper = new EntityWrapper<>();
            orderWrapper.eq("customer_order_id", shippingInfoBO.getVcshipno());
            List<Order> orderList = baseMapper.selectListNoTenant(orderWrapper);
            // 如果订单不存在就插入，存在则更新
            if (CollectionUtils.isEmpty(orderList)) {
                // 插入
                createOrder(authorization, shippingInfoBO, Long.valueOf(tenantId));
            }
        }
    }

    //转换板车类型名字
    private String getTrailerTypeName(String trailerTypeName) {
        if (StringUtils.isNotBlank(trailerTypeName)) {
            if (trailerTypeName.equals("平板三位板")) {
                return "三位平板";
            }
            if (trailerTypeName.equals("平板四位板")) {
                return "四位平板";
            }
            if (trailerTypeName.equals("六位车")) {
                return "六位平板";
            }
            if (trailerTypeName.equals("单车")) {
                return "单车";
            }
            if (trailerTypeName.equals("中置轴")) {
                return "中置轴";
            }
            if (trailerTypeName.equals("七位车")) {
                return "七位平板";
            }
            if (trailerTypeName.equals("人送地跑")) {
                return "人送地跑";
            }
            if (trailerTypeName.equals("铁路J车")) {
                return "铁运J车";
            }
            if (trailerTypeName.equals("铁运板架箱")) {
                return "铁路板架厢";
            }
            if (trailerTypeName.equals("救援车")) {
                return "救援车";
            }
            if (trailerTypeName.equals("船运")) {
                return "水运";
            }
            if (trailerTypeName.equals("平板五位板")) {
                return "五位平板";
            }
        }
        return trailerTypeName;
    }

    /**
     * 获取交货点地址
     */
    private LocationVo endLocation(ShipmentInfoVO shipmentInfo, Long teanantId, String authorization) {
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
        // 判断订单明细里的交货地点信息是否存在，不存在则插入
        LocationVo endLocation = locationService.getLocationByName("交货点", shipmentInfo.getDestLocationName(),shipmentInfo.getDestLocationId());
        if (endLocation == null) {
            Map<String, String> params = new HashMap<>();
            params.put("province", shipmentInfo.getDestLocationProvince());
            params.put("city", shipmentInfo.getDestLocationCity());
            String county = shipmentInfo.getDestLocationCounty();
            if (StringUtils.isNotBlank(county)) {
                params.put("county", county);
            }
            String result = null;
            try {
                LOGGER.info("连接Integration 获取的地编码 url:{} param:{}", integrationUrl + queryListOriginationUrl, JSONObject.toJSONString(params));

                result = HttpClientUtil.postJson(integrationUrl + queryListOriginationUrl, headNamePairs, JSONObject.toJSONString(params), socketTimeout);
            } catch (Exception e) {
                LOGGER.error("连接Integration 获取目的地编码失败 error:{}", e);
                return null;
            }
            if (StringUtils.isBlank(result)) {
                LOGGER.error("连接Integration 获取目的地编码未响应 error");
                return null;
            }
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (Objects.nonNull(jsonObject)) {
                String data = jsonObject.getString("data");
                if (!StringUtils.isEmpty(data)) {
                    List<OriginationDTO> originationDTOS = JSONObject.parseArray(data, OriginationDTO.class);
                    String label = shipmentInfo.getDestLocationProvince() + shipmentInfo.getDestLocationCity() +
                            (StringUtils.isNotBlank(shipmentInfo.getDestLocationCounty()) ? shipmentInfo.getDestLocationCounty() : "");
                    HashMap<String, String> param = Maps.newHashMap();
                    param.put("typeValue", "交货点");
                    param.put("value", StringUtils.isBlank(shipmentInfo.getDestLocationAddress()) ?
                            shipmentInfo.getDestLocationName() : shipmentInfo.getDestLocationAddress());//调整value 存储详细地址
                    param.put("label", label);
                    param.put("province", shipmentInfo.getDestLocationProvince());
                    param.put("city", shipmentInfo.getDestLocationCity());
                    param.put("county", shipmentInfo.getDestLocationCounty());
                    param.put("tenantId", String.valueOf(teanantId));
                    param.put("name", shipmentInfo.getDestLocationId());
                    if (!StringUtils.isEmpty(originationDTOS.get(0).getCountyCode())) {
                        //调整省市区 组装订单
                        param.put("adCode", originationDTOS.get(0).getCountyCode());
                        endLocation = locationService.insertOrUpdateLocationOTM(param);
                    } else {
                        param.put("adCode", originationDTOS.get(0).getCityCode());
                        endLocation = locationService.insertOrUpdateLocationOTM(param);
                    }
                }

            }
        }

        return endLocation;
    }

    /**
     * 获取发货点地址
     */
    private LocationVo startLocation(ShipmentInfoVO shipmentInfo, Long teanantId, String authorization) {
        // 判断订单明细里的提货地点信息是否存在，不存在则插入
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
        LocationVo startLocation = locationService.getLocationByName("发货点", shipmentInfo.getOriginLocationName(),shipmentInfo.getOriginLocationId());
        if (startLocation == null) {
            Map<String, String> params = new HashMap<>();
            params.put("province", shipmentInfo.getOriginLocationProvince());
            params.put("city", shipmentInfo.getOriginLocationCity());
            String county = shipmentInfo.getOriginLocationCounty();
            if (StringUtils.isNotBlank(county)) {
                params.put("county", county);
            }
            String result = null;
            try {
                LOGGER.info("连接Integration 获取启运地编码 url:{} param:{}", integrationUrl + queryListOriginationUrl, JSONObject.toJSONString(params));
                result = HttpClientUtil.postJson(integrationUrl + queryListOriginationUrl,
                        headNamePairs, JSONObject.toJSONString(params),
                        socketTimeout);
            } catch (Exception e) {
                LOGGER.error("连接Integration 获取启运地编码失败 error:{}", e);
                return null;
            }
            if (StringUtils.isBlank(result)) {
                LOGGER.error("连接Integration 获取启运地编码未响应 error");
                return null;
            }
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (Objects.nonNull(jsonObject)) {
                String data = jsonObject.getString("data");
                if (!StringUtils.isEmpty(data)) {
                    List<OriginationDTO> originationDTOS = JSONObject.parseArray(data, OriginationDTO.class);
                    String label = shipmentInfo.getOriginLocationProvince() + shipmentInfo.getOriginLocationCity() +
                            (StringUtils.isNotBlank(shipmentInfo.getOriginLocationCounty()) ? shipmentInfo.getOriginLocationCounty() : "");
                    HashMap<String, String> param = Maps.newHashMap();
                    param.put("typeValue", "发货点");
                    param.put("value", StringUtils.isBlank(shipmentInfo.getOriginLocationAddress()) ?
                            shipmentInfo.getOriginLocationName() : shipmentInfo.getOriginLocationAddress());//调整value 存储详细地址
                    param.put("label", label);
                    param.put("province", shipmentInfo.getOriginLocationProvince());
                    param.put("city", shipmentInfo.getOriginLocationCity());
                    param.put("county", shipmentInfo.getOriginLocationCounty());
                    param.put("tenantId", String.valueOf(teanantId));
                    param.put("name", shipmentInfo.getOriginLocationId());
                    if (!StringUtils.isEmpty(originationDTOS.get(0).getCountyCode())) {
                        //调整省市区 组装订单
                        param.put("adCode", originationDTOS.get(0).getCountyCode());
                        startLocation = locationService.insertOrUpdateLocationOTM(param);
                    } else {
                        param.put("adCode", originationDTOS.get(0).getCityCode());
                        startLocation = locationService.insertOrUpdateLocationOTM(param);
                    }
                }

            }
        }
        return startLocation;
    }

    @Override
    @Transactional
    public void addEmptyOrder(ShipmentInfoVO infoDTO, String token) {
        if (infoDTO == null) {
            return;
        }
        // 无车牌
        if (!StringUtils.isNotBlank(infoDTO.getPlateNo())) {
            return;
        }
        // 查询牵引车基本信息
        CarrierInfoLineVO carrierInfoLineVO = selectCarrierInfoByPlate(infoDTO.getPlateNo());
        if (null == carrierInfoLineVO) {
            return;
        }
        // 无承运商ID和名
        if (!Objects.nonNull(carrierInfoLineVO.getLspId()) || !StringUtils.isNotEmpty(carrierInfoLineVO.getLspName())) {
            return;
        }
        // 获取登录者信息
//        String tokenNew = StringUtils.substringAfter(token, "Bearer ");
//        JwtAccountVO accountVO = JwtTokenUtil.decodeJwt(tokenNew);
        Long tenantId = Long.valueOf(carrierInfoLineVO.getTenantId());

        infoDTO.setDriverMoble(carrierInfoLineVO.getDriverMobile());
        infoDTO.setDriverId(String.valueOf(carrierInfoLineVO.getDriverId()));
        infoDTO.setTenantId(tenantId);
        infoDTO.setCreator("unlcn");

        // 空放处理方式（增删改）
        if (StringUtils.isEmpty(infoDTO.getTransactionCode())) {
            LOGGER.info("数据处理方式为空");
            return;
        }

        switch (infoDTO.getTransactionCode()) {
            case "IU":
                if (!insertEmptyOrder(infoDTO, carrierInfoLineVO, token)) {
                    return;
                }
                break;
            case "R":
                if (!updateEmptyOrder(infoDTO, carrierInfoLineVO, token)) {
                    return;
                }
                break;
            default:
                if (!deleteEmptyOrder(infoDTO, token)) {
                    return;
                }
                break;
        }
        orderToErp(infoDTO, token);

    }

    /**
     * 删除空放指令订单
     *
     * @param shipmentInfoVO
     * @param authorization
     * @return
     */
    private Boolean deleteEmptyOrder(ShipmentInfoVO shipmentInfoVO, String authorization) {
        //指令是否已存在-不存在新增-存在更新
        EntityWrapper<Order> orderEW = new EntityWrapper<>();
        orderEW.eq("customer_id", "unlcn")
                .eq("customer_order_id", shipmentInfoVO.getShipmentId())
                .eq("is_delete", TableStatusEnum.STATUS_0.getCode());
        List<Order> orders = selectList(orderEW);
        if (null == orders || orders.size() == 0) {
            // 不存在
            return false;
        }

        // 更新order
        for (Order order : orders) {
            order.setIsDelete(1);
            this.updateById(order);

            Wrapper<OrderAssign> orderAssignWrapper = new EntityWrapper<>();
            orderAssignWrapper.eq("order_code", order.getCode());
            OrderAssign orderAssign = orderAssignService.selectOne(orderAssignWrapper);
            List<OrderAssign> orderAssigns = orderAssignService.selectList(orderAssignWrapper);
            for (OrderAssign updateOrderAssign : orderAssigns) {
                updateOrderAssign.setIsDelete(1);
                orderAssignService.updateById(updateOrderAssign);
            }
            Wrapper<OrderContact> orderContactWrapper = new EntityWrapper<>();
            orderContactWrapper.eq("order_code", order.getCode());
            OrderContact orderContact = new OrderContact();
            orderContact.setIsDelete(1);
            orderContactService.update(orderContact, orderContactWrapper);

            Wrapper<OrderItem> orderItemWrapper = new EntityWrapper<>();
            orderItemWrapper.eq("order_id", order.getId());
            OrderItem orderItem = new OrderItem();
            orderItem.setIsDelete(1);
            orderItemService.update(orderItem, orderItemWrapper);

            Wrapper<OrderLocation> orderLocationWrapper = new EntityWrapper<>();
            orderLocationWrapper.eq("order_id", order.getId());
            OrderLocation orderLocation = new OrderLocation();
            orderLocation.setIsDelete(1);
            orderLocationService.update(orderLocation, orderLocationWrapper);
            //删除收入价格
//            deletePriceIncoming(order.getCode(), authorization, shipmentInfoVO);
//             LOGGER.info("删除指令调用TMS --->url:{},param:{}", addShipmentURL, JSON.toJSONString(shipmentOrderDTO));
            //下订单，自动生成TMS的运单、任务和装车单

            if (org.springframework.util.StringUtils.isEmpty(orderAssign.getConsignCode()))
                throw new BaseException("运单编号不能为空");
            Wrapper<ShipOrder> shipOrderWrapper = new EntityWrapper<>();
            shipOrderWrapper.eq("code", orderAssign.getConsignCode());
            ShipOrder shipOrder = new ShipOrder();
            shipOrder.setIsDelete(1);
            shipOrderService.update(shipOrder, shipOrderWrapper);

            Wrapper<ShipOrderItem> shipOrderItemWrapper = new EntityWrapper<>();
            shipOrderItemWrapper.eq("ship_order_code", orderAssign.getConsignCode());
            ShipOrderItem shipOrderItem = new ShipOrderItem();
            shipOrderItem.setIsDelete(1);
            shipOrderItemService.update(shipOrderItem, shipOrderItemWrapper);

            Wrapper<ShipTask> shipTaskWrapper = new EntityWrapper<>();
            shipTaskWrapper.eq("ship_order_code", orderAssign.getConsignCode());
            ShipTask shipTask = new ShipTask();
            shipTask.setIsDelete(1);
            ShipTask oldshipTask = shipTaskService.selectOne(shipTaskWrapper);
            shipTaskService.update(shipTask, shipTaskWrapper);

            Wrapper<ShipTaskContact> shipTaskContactWrapper = new EntityWrapper<>();
            shipTaskContactWrapper.eq("ship_task_code", oldshipTask.getCode());
            ShipTaskContact shipTaskContact = new ShipTaskContact();
            shipTaskContact.setIsDelete(1);
            shipTaskContactService.update(shipTaskContact, shipTaskContactWrapper);

            Wrapper<ShipTaskLocation> shipTaskLocationWrapper = new EntityWrapper<>();
            shipTaskLocationWrapper.eq("ship_task_code", oldshipTask.getCode());
            ShipTaskLocation shipTaskLocation = new ShipTaskLocation();
            shipTaskLocation.setIsDelete(1);
            shipTaskLocationService.update(shipTaskLocation, shipTaskLocationWrapper);

            Wrapper<ShipmentDetail> shipmentDetailWrapper = new EntityWrapper<>();
            shipmentDetailWrapper.eq("ship_task_code", oldshipTask.getCode());
            ShipmentDetail shipmentDetail = new ShipmentDetail();
            shipmentDetail.setIsDelete(1);
            ShipmentDetail oldshipmentDetail = shipmentDetailService.selectOne(shipmentDetailWrapper);
            shipmentDetailService.update(shipmentDetail, shipmentDetailWrapper);
            Wrapper<ShipmentDetail> shipmentDetailEntityWrapper = new EntityWrapper<>();
            shipmentDetailEntityWrapper.eq("shipment_id", oldshipmentDetail.getShipmentId());
            List<ShipmentDetail> shipmentDetailList = shipmentDetailService.selectList(shipmentDetailEntityWrapper);
            int isOk = 0;
            for (ShipmentDetail shipmentDetail1 : shipmentDetailList) {
                if (shipmentDetail1.getIsDelete() == 0) {
                    isOk = 1;
                    break;
                }
            }
            if (isOk == 1) return true;
            Wrapper<Shipment> shipmentWrapper = new EntityWrapper<>();
            shipmentWrapper.eq("id", oldshipmentDetail.getShipmentId());
            Shipment shipment = new Shipment();
            shipment.setIsDelete(1);
            shipmentService.update(shipment, shipmentWrapper);
        }

        return true;
    }

    /**
     * 更新空放指令订单
     *
     * @param shipmentInfoVO
     * @param authorization
     * @return
     */
    private Boolean updateEmptyOrder(ShipmentInfoVO shipmentInfoVO, CarrierInfoLineVO carrierInfoLineVO, String
            authorization) {
        //指令是否已存在-不存在新增-存在更新
        EntityWrapper<Order> orderEW = new EntityWrapper<>();
        orderEW.eq("customer_id", "unlcn")
                .eq("customer_order_id", shipmentInfoVO.getShipmentId())
                .eq("is_delete", TableStatusEnum.STATUS_0.getCode());
        List<Order> orders = selectList(orderEW);
        if (null == orders || orders.size() == 0) {
            // 不存在添加
            shipmentInfoVO.setTransactionCode("IU");
            insertEmptyOrder(shipmentInfoVO, carrierInfoLineVO, authorization);
            return false;
        }

        //获取运输方式id
        Long transTypeId = getTransTypeId(shipmentInfoVO.getTransportModeId());
        if (null == transTypeId) {
            LOGGER.error("未查询到对应的运输方式 error:{}", shipmentInfoVO.getTransportModeId());
        }

        // 更新order
        Order order = orders.get(0);
        addOrder(shipmentInfoVO, transTypeId, order);

        // 生成或更新订单联系人lisa_order_contact
        Wrapper<OrderContact> orderContactEW = new EntityWrapper<>();
        orderContactEW.eq("order_code", order.getCode())
                .eq("is_delete", TableStatusEnum.STATUS_0.getCode());
        OrderContact orderContact = orderContactService.selectOne(orderContactEW);
        addOrderContactNew(carrierInfoLineVO, shipmentInfoVO.getTenantId(), order, orderContact);

        // 生成或更新订单地址lisa_order_location
        Wrapper<OrderLocation> orderLocationEW = new EntityWrapper<>();
        orderLocationEW.eq("order_id", order.getId())
                .eq("is_delete", TableStatusEnum.STATUS_0.getCode());
        OrderLocation orderLocation = orderLocationService.selectOne(orderLocationEW);
        addOrderLocation(shipmentInfoVO, authorization, order, orderLocation);

        // 生成或更新订单lisa_order_item
        Wrapper<OrderItem> orderItemEW = new EntityWrapper<>();
        orderItemEW.eq("order_id", order.getId())
                .eq("is_delete", TableStatusEnum.STATUS_0.getCode());
        OrderItem orderItem = orderItemService.selectOne(orderItemEW);
        addOrderItem(shipmentInfoVO.getTenantId(), order, orderContact, orderItem);

        // 生成或更新装车单 lisa_shipment(一个指令一个装车单一个订单)
        Wrapper<Shipment> shipmentEW = new EntityWrapper<>();
        shipmentEW.eq("ship_source_key", shipmentInfoVO.getShipmentId())
                .eq("is_delete", TableStatusEnum.STATUS_0.getCode());
        Shipment shipment = shipmentService.selectOne(shipmentEW);
        addShipment(shipmentInfoVO, carrierInfoLineVO, authorization, transTypeId, shipment);

        // 生成或更新装车单跟运单关系 lisa_shipment_detail
        Wrapper<ShipmentDetail> shipmentDetailEW = new EntityWrapper<>();
        shipmentDetailEW.eq("shipment_id", shipment.getId())
                .eq("is_delete", TableStatusEnum.STATUS_0.getCode());
        ShipmentDetail shipmentDetail = shipmentDetailService.selectOne(shipmentDetailEW);

        // 生成或更新订单下发 lisa_order_assign
        Wrapper<OrderAssign> orderAssignEW = new EntityWrapper<>();
        orderAssignEW.eq("order_code", order.getCode())
                .eq("is_delete", TableStatusEnum.STATUS_0.getCode());
        OrderAssign orderAssign = orderAssignService.selectOne(orderAssignEW);
        // 生成或更新运单 lisa_ship_order(每个订单生成一个运单)
        Wrapper<ShipOrder> shipOrderEW = new EntityWrapper<>();
        shipOrderEW.eq("code", orderAssign.getConsignCode())
                .eq("is_delete", TableStatusEnum.STATUS_0.getCode());
        ShipOrder shipOrder = shipOrderService.selectOne(shipOrderEW);
        addShipOrder(shipmentInfoVO.getTenantId(), shipOrder);
        addOrderAssign(shipmentInfoVO.getTenantId(), order, orderItem, shipOrder, orderAssign);

        // 生成或更新任务 lisa_ship_task
        Wrapper<ShipTask> shipTaskEW = new EntityWrapper<>();
        shipTaskEW.eq("ship_source_key", shipmentInfoVO.getShipmentId())
                .eq("is_delete", TableStatusEnum.STATUS_0.getCode());
        ShipTask shipTask = shipTaskService.selectOne(shipTaskEW);
        addShipTask(carrierInfoLineVO, shipmentInfoVO.getTenantId(), transTypeId, shipOrder, shipTask);

        // 按订单明细生成或更新运单明细 lisa_ship_order_item
        Wrapper<ShipOrderItem> shipOrderItemEW = new EntityWrapper<>();
        shipOrderItemEW.eq("order_code", order.getCode())
                .eq("is_delete", TableStatusEnum.STATUS_0.getCode());
        ShipOrderItem shipOrderItem = shipOrderItemService.selectOne(shipOrderItemEW);
        addShipOrderItem(shipmentInfoVO.getTenantId(), orderItem, shipOrder, shipOrderItem);

        // 生成或更新运输任务联系人 lisa_ship_task_contact
        Wrapper<ShipTaskContact> shipTaskContactEW = new EntityWrapper<>();
        shipTaskContactEW.eq("ship_task_code", shipTask.getCode())
                .eq("is_delete", TableStatusEnum.STATUS_0.getCode());
        ShipTaskContact shipTaskContact = shipTaskContactService.selectOne(shipTaskContactEW);
        addShipTaskContact(shipmentInfoVO.getTenantId(), orderContact, shipTask, shipTaskContact);

        // 生成或更新运输任务起止点信息 lisa_ship_task_location
        Wrapper<ShipTaskLocation> shipTaskLocationEW = new EntityWrapper<>();
        shipTaskLocationEW.eq("ship_task_code", shipTask.getCode())
                .eq("is_delete", TableStatusEnum.STATUS_0.getCode());
        ShipTaskLocation shipTaskLocation = shipTaskLocationService.selectOne(shipTaskLocationEW);
        addShipTaskLocation(shipmentInfoVO.getTenantId(), orderLocation, shipTask, shipTaskLocation);


        return true;
    }

    /**
     * 添加空放指令订单
     */
    private Boolean insertEmptyOrder(ShipmentInfoVO shipmentInfoVO, CarrierInfoLineVO carrierInfoLineVO, String
            authorization) {

        //重复校验
        EntityWrapper<Order> orderEW = new EntityWrapper<>();
        orderEW.eq("customer_id", "unlcn")
                .eq("customer_order_id", shipmentInfoVO.getShipmentId())
                .eq("is_delete", TableStatusEnum.STATUS_0.getCode());
        int count = selectCountNotenant(orderEW);
        //存在先删除在添加
        if (count > 0) {
            deleteEmptyOrder(shipmentInfoVO, authorization);
        }

        //获取运输方式id
        Long transTypeId = getTransTypeId(shipmentInfoVO.getTransportModeId());
        if (null == transTypeId) {
            LOGGER.error("未查询到对应的运输方式 error:{}", shipmentInfoVO.getTransportModeId());
        }
        // 生成或更新订单 lisa_order
        Order order = new Order();
        addOrder(shipmentInfoVO, transTypeId, order);
        // 生成或更新订单联系人lisa_order_contact
        OrderContact orderContact = new OrderContact();
        addOrderContactNew(carrierInfoLineVO, shipmentInfoVO.getTenantId(), order, orderContact);
        // 生成或更新订单地址lisa_order_location
        OrderLocation orderLocation = new OrderLocation();
        addOrderLocation(shipmentInfoVO, authorization, order, orderLocation);
        // 生成或更新订单lisa_order_item
        OrderItem orderItem = new OrderItem();
        addOrderItem(shipmentInfoVO.getTenantId(), order, orderContact, orderItem);

        // 生成或更新装车单 lisa_shipment(一个指令一个装车单一个订单)
        Shipment shipment = new Shipment();
        addShipment(shipmentInfoVO, carrierInfoLineVO, authorization, transTypeId, shipment);
        // 生成或更新运单 lisa_ship_order(每个订单生成一个运单)
        ShipOrder shipOrder = new ShipOrder();
        addShipOrder(shipmentInfoVO.getTenantId(), shipOrder);
        // 生成或更新任务 lisa_ship_task
        ShipTask shipTask = new ShipTask();
        addShipTask(carrierInfoLineVO, shipmentInfoVO.getTenantId(), transTypeId, shipOrder, shipTask);
        // 按订单明细生成或更新运单明细 lisa_ship_order_item
        ShipOrderItem shipOrderItem = new ShipOrderItem();
        addShipOrderItem(shipmentInfoVO.getTenantId(), orderItem, shipOrder, shipOrderItem);
        // 生成或更新订单下发 lisa_order_assign
        OrderAssign orderAssign = new OrderAssign();
        addOrderAssign(shipmentInfoVO.getTenantId(), order, orderItem, shipOrder, orderAssign);
        // 生成或更新运输任务联系人 lisa_ship_task_contact
        ShipTaskContact shipTaskContact = new ShipTaskContact();
        addShipTaskContact(shipmentInfoVO.getTenantId(), orderContact, shipTask, shipTaskContact);
        // 生成或更新运输任务起止点信息 lisa_ship_task_location
        ShipTaskLocation shipTaskLocation = new ShipTaskLocation();
        addShipTaskLocation(shipmentInfoVO.getTenantId(), orderLocation, shipTask, shipTaskLocation);
        // 生成或更新装车单跟运单关系 lisa_shipment_detail
        ShipmentDetail shipmentDetail = new ShipmentDetail();
        addShipmentDetail(shipmentInfoVO.getTenantId(), shipment, shipTask, shipmentDetail);

        return true;
    }

    private ShipmentDetail addShipmentDetail(Long tenantId, Shipment shipment, ShipTask shipTask, ShipmentDetail
            shipmentDetail) {
        // 装车单 id
        shipmentDetail.setShipmentId(shipment.getId());
        // 任务编号
        shipmentDetail.setShipTaskCode(shipTask.getCode());
        // 运输任务开始顺序
        shipmentDetail.setShipTaskOriginOrder(0);
        // 运输任务结束顺序
        shipmentDetail.setShipTaskDestOrder(0);
        shipmentDetail.setTenantId(tenantId);
        shipmentDetailService.insertOrUpdate(shipmentDetail);
        return shipmentDetail;
    }

    private ShipTaskLocation addShipTaskLocation(Long tenantId, OrderLocation orderLocation, ShipTask
            shipTask, ShipTaskLocation shipTaskLocation) {
        shipTaskLocation.setShipTaskCode(shipTask.getCode());
        // 起点对应的location code
        shipTaskLocation.setOriginLocationCode(String.valueOf(orderLocation.getShippingLocationId()));
        // 终点对应的location code
        shipTaskLocation.setDestLocationCode(String.valueOf(orderLocation.getDeliveryLocationId()));
        shipTaskLocation.setTenantId(tenantId);
        shipTaskLocationService.insertOrUpdate(shipTaskLocation);
        return shipTaskLocation;
    }

    private ShipTaskContact addShipTaskContact(Long tenantId, OrderContact orderContact, ShipTask
            shipTask, ShipTaskContact shipTaskContact) {
        shipTaskContact.setDestContactName(orderContact.getContactsName());
        shipTaskContact.setDestContactPhone(orderContact.getContactsPhone());
        shipTaskContact.setOriginContactName(orderContact.getContactsName());
        shipTaskContact.setOriginContactPhone(orderContact.getContactsPhone());
        shipTaskContact.setShipTaskCode(shipTask.getCode());
        shipTaskContact.setTenantId(tenantId);
        shipTaskContactService.insertOrUpdate(shipTaskContact);
        return shipTaskContact;
    }

    private OrderAssign addOrderAssign(Long tenantId, Order order, OrderItem orderItem, ShipOrder
            shipOrder, OrderAssign orderAssign) {
        orderAssign.setOrderCode(order.getCode());
        orderAssign.setOrderItemCode(orderItem.getId());
        orderAssign.setConsignCode(shipOrder.getCode());
        orderAssign.setGmtConsign(shipOrder.getGmtCreate());
        orderAssign.setGmtAssign(new Date());
        orderAssign.setAssignLog("成功");
        orderAssign.setTenantId(tenantId);
        orderAssignService.insertOrUpdate(orderAssign);
        return orderAssign;
    }

    private ShipOrderItem addShipOrderItem(Long tenantId, OrderItem orderItem, ShipOrder shipOrder, ShipOrderItem
            shipOrderItem) {
        shipOrderItem.setShipOrderCode(shipOrder.getCode());
        shipOrderItem.setOrderItemId(orderItem.getId());
        shipOrderItem.setTenantId(tenantId);
        shipOrderItem.setIssueItemId(orderItem.getIssueItemId());
        shipOrderItem.setMaterial(orderItem.getMaterial());
        shipOrderItem.setItemSourceKey(orderItem.getItemSourceKey());
        shipOrderItemService.insertOrUpdate(shipOrderItem);
        return shipOrderItem;
    }

    private ShipTask addShipTask(CarrierInfoLineVO carrierInfoLineVO, Long tenantId, Long transTypeId, ShipOrder
            shipOrder, ShipTask shipTask) {
        shipTask.setCode("ST" + snowFlakeId.nextId());
        shipTask.setShipOrderCode(shipOrder.getCode());
        shipTask.setCarrierId(carrierInfoLineVO.getId().toString());
        shipTask.setTenantId(Integer.valueOf(tenantId.toString()));
        shipTask.setTransTypeId(null == transTypeId ? 0L : transTypeId);
        shipTaskService.insertOrUpdate(shipTask);
        return shipTask;
    }

    private ShipOrder addShipOrder(Long tenantId, ShipOrder shipOrder) {
        shipOrder.setTenantId(tenantId);
        shipOrder.setCode("SO" + snowFlakeId.nextId());
        shipOrderService.insertOrUpdate(shipOrder);
        return shipOrder;
    }

    private Shipment addShipment(ShipmentInfoVO shipmentInfoVO, CarrierInfoLineVO carrierInfoLineVO, String
            authorization, Long transTypeId, Shipment shipment) {
        shipment.setCode("SP" + snowFlakeId.nextId());
        shipment.setTenantId(shipmentInfoVO.getTenantId());
        shipment.setTransTypeId(null == transTypeId ? 0L : transTypeId);
        shipment.setLspId(carrierInfoLineVO.getLspId().toString());
        shipment.setLspName(carrierInfoLineVO.getLspName());
        if (null != carrierInfoLineVO.getFleetId()) {
            shipment.setFleetId(carrierInfoLineVO.getFleetId().toString());
            shipment.setFleetName(carrierInfoLineVO.getFleetName());
        }
        if (Objects.nonNull(carrierInfoLineVO.getId())) {
            shipment.setCarrierId(carrierInfoLineVO.getId().toString());
        }
        shipment.setTransportationId(shipmentInfoVO.getPlateNo());
        shipment.setDriverId(String.valueOf(carrierInfoLineVO.getDriverId()));
        shipment.setShipSourceKey(shipmentInfoVO.getShipmentId());
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
        String result = HttpClientUtil.get(getDriverInfoById + "/" + carrierInfoLineVO.getDriverId() + "/" + 0, headNamePairs, null, socketTimeout);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (result==null || "".equals(result)){
            throw new BaseException("获取牵引车及司机信息连接超时");
        }
        if (jsonObject.getInteger("code") != 0) {
            throw new BaseException(jsonObject.get("message").toString());
        }
        shipment.setDriverName(jsonObject.getJSONObject("data").getString("name"));
        shipment.setDriverPhone(jsonObject.getJSONObject("data").getString("mobile"));
        shipmentService.insertOrUpdate(shipment);
        return shipment;
    }

    private OrderItem addOrderItem(Long tenantId, Order order, OrderContact orderContact, OrderItem orderItem) {
        orderItem.setOrderId(order.getId());
        orderItem.setAmount(0);
        orderItem.setUom("辆");
        orderItem.setIssueItemId(null);
        orderItem.setMaterial(null);
        orderItem.setTenantId(tenantId);
        orderItem.setGmtCreate(new Date());
        orderItem.setOwnerName(orderContact.getContactsName());
        orderItem.setItemSourceKey(null);
        orderItemService.insertOrUpdate(orderItem);
        return orderItem;
    }

    private OrderLocation addOrderLocation(ShipmentInfoVO shipmentInfoVO, String authorization, Order
            order, OrderLocation orderLocation) {
        List<LocationVo> locationVoList = new ArrayList<>();
        LocationVo endLocation = endLocation(shipmentInfoVO, shipmentInfoVO.getTenantId(), authorization);
        if (endLocation == null) {
            LOGGER.error("获取交货点信息失败");
        }
        shipmentInfoVO.setEndLocation(endLocation);
        locationVoList.add(endLocation);
        LocationVo startLocation = startLocation(shipmentInfoVO, shipmentInfoVO.getTenantId(), authorization);
        if (startLocation == null) {
            LOGGER.error("获取发货点信息失败");
        }
        shipmentInfoVO.setStartLocation(startLocation);
        locationVoList.add(startLocation);
        order.setLocation(locationVoList);
        //订单地址
        orderLocation.setOrderId(order.getId());
        orderLocation.setShippingLocationId(null == startLocation.getId() ? 0L : startLocation.getId());
        orderLocation.setDeliveryLocationId(null == endLocation.getId() ? 0L : endLocation.getId());
        orderLocation.setGmtCreate(new Date());
        orderLocation.setTenantId(shipmentInfoVO.getTenantId());
        orderLocationService.insertOrUpdate(orderLocation);
        return orderLocation;
    }

    private Order addOrder(ShipmentInfoVO shipmentInfoVO, Long transTypeId, Order order) {

        order.setCode("CO" + snowFlakeId.nextId());
        order.setComment("空放订单");
        order.setTos("fleet");
        order.setGmtIssue(new Date());
        order.setGmtCreate(new Date());
        order.setCustomerOrderId(shipmentInfoVO.getShipmentId());
        order.setTransTypeId(transTypeId);
        order.setTenantId(shipmentInfoVO.getTenantId());
        order.setCurrentStatus(shipmentInfoVO.getStatus());
        order.setCustomerId("unlcn");
        order.setCustomerName("中联物流");
        this.insertOrUpdate(order);
        shipmentInfoVO.setOrderCode(order.getCode());
        return order;
    }

}
